我想从c#specflow表创建一个字典。我需要这个,因为标签和值中的值将针对每个特征文件而改变。在我当前的特征文件中,我有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);
}``
目前我在此处无效。请帮助。
答案 0 :(得分:2)
如果您希望灵活使用表格列标题:
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();
答案 1 :(得分:0)
如果每个键只有一个值
,请尝试以下操作 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());