c# - 将 specflow 表转换为字典

标签 c# linq specflow

我想从 c# specflow 表创建字典。我需要这个,因为标签中的值和每个特征文件的值都会发生变化。在我当前的特征文件中,我有 2 列。

And I submit with following 
| Label         | Value               |
| Namelabel     | texttoenter123      |
| Email         |test@test.com        |

对应步骤。尝试使用linq。

 [When(@"I submit with following ")]

   public void WhenISubmitWithFollowing(Table table)
        {
       //Should be something like this , which convert the table todictionary object
          var x = table.Rows.ToDictionary(k=>k.Keys,k=>k.Values);
        }``

目前我在这方面得到了空值。请帮忙。

最佳答案

如果您想灵活使用表格列标题:

var x = table.Rows.ToDictionary(r => r[0], r => r[1]);

否则:

var x = table.Rows.ToDictionary(r => r["Label"], r => r["Value"]);

如果你想要一个对 TechTalk.SpecFlow.Table 的快速扩展方法:

static class SpecFlowExtensions
{
    /// <summary>
    /// Converts a two column Gherkin data table to a dictionary
    /// </summary>
    /// <param name="table"></param>
    /// <returns></returns>
    public static Dictionary<string, string> ToDictionary(this Table table)
    {
        if (table == null)
            throw new ArgumentNullException(nameof(table));

        if (table.Rows.Count == 0)
            throw new InvalidOperationException("Gherkin data table has no rows");

        if (table.Rows.First().Count != 2)
            throw new InvalidOperationException($@"Gherkin data table must have exactly 2 columns. Columns found: ""{string.Join(@""", """, table.Rows.First().Keys)}""");

        return table.Rows.ToDictionary(row => row[0], row => row[1]);
    }
}

并使用扩展方法:

var data = table.ToDictionary();

关于c# - 将 specflow 表转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47503580/

相关文章:

c# - 我怎样才能进行内联排序?

c# - 在特定条件下跳过 specflow 规范

BDD SpecFlow 场景类型

xslt - SpecFlow 的自定义报告

c# - 获取Windows 8自动颜色主题的激活颜色

c# - 使用 Web 服务 C#?

linq - 将表达式传递给 NHibernate 中的方法会导致类型 'ConstantExpression' 的对象无法转换为类型 'LambdaExpression'

c# - 使用 NuGet 将依赖关系限制为特定 .NET 版本

c# - 在 TextBox 中启用除最后 N 个字符之外的密码字符/限制屏蔽字符

c# - Linq 表达式和 "Not Contains"查询