将 specflow table 转换为字典

Convert specflow table todictionary

我想从 c# specflow table 创建字典。我需要这个,因为标签中的值和每个功能的值都会改变 file.In 我当前的功能文件,我有 2 列。

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

对应Step.Tried使用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);
        }``

目前我在 this.Please 帮助中得到 null。

如果每个键只有一个值,请尝试以下操作

            DataTable dt = new DataTable();
            dt.Columns.Add("Label", typeof(string));
            dt.Columns.Add("Value", typeof(string));


            dt.Rows.Add(new object[] { "Namelabel", "texttoenter123" });
            dt.Rows.Add(new object[] { "Email", "test@test.com" });

            Dictionary<string, string> dict = dt.AsEnumerable()
                .GroupBy(x => x.Field<string>("Label"), y => y.Field<string>("Value"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

如果每个键有多个值,请使用以下内容

            Dictionary<string, List<string>> dict = dt.AsEnumerable()
                .GroupBy(x => x.Field<string>("Label"), y => y.Field<string>("Value"))
                .ToDictionary(x => x.Key, y => y.ToList());

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

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();