我有一个带有以下测试数据的规格流测试
| Field | Value |
| Message | test |
| Message2| test2 |
我有一个从规范流表中获取数据的类
public List<String> GetInputMessage(Table table)
{
var elements = new List<string>();
var data = table.CreateSet<SpecFlowData>().ToList();
elements.AddRange(from item in data
let field = item.Field
let value = item.Value
select new List<string>(new string[] { field ,value}));
return elements;
}
但我收到错误:
无法从
'System.Collections.Generic.IEnumerable <System.Collections.Generic.List<string>>'
转换为System.Collections.Generic.IEnumerable<string>
从表中获取字段和值的另一种方法是什么?谢谢
答案 0 :(得分:2)
您的字段名称和值对似乎是字典集合的良好匹配,而不是列表集合。
public Dictionary<string, string> GetInputMessage(Table table)
{
var elements = new Dictionary<string, string>();
foreach(var item in table.CreateSet<SpecFlowData>())
{
elements.Add(item.Field, item.Value);
}
return elements;
}
答案 1 :(得分:1)
AddRange
方法期待IEnumerable<string>
,但您尝试传递IEnumerable<List<string>>
。试试这个:
elements.AddRange(data.SelectMany(x => new [] { x.Field, x.Value}));
或者,如果您想将Field
和Value
连接成一行:
elements.AddRange(data.Select(x => string.Join(",", x.Field,x.Value));
答案 2 :(得分:1)
虽然接受的答案显示了如何使用字典,但如果您有多个相同的Field
,则无法使用它。在这种情况下,我只会创建一个代表每一行的类,它不是很多代码,而且与原始答案非常相似(我还清理了一些删除了一些你不需要的额外位)。
//Add this somewhere in your project.
class MyDataRow
{
public string Field {get; set;}
public string Value {get; set;}
}
//back to your orginal function.
public List<MyDataRow> GetInputMessage(Table table)
{
var data = table.CreateSet<SpecFlowData>(); //the ToList() that was here is not needed, just use the IEnumerable<SpecFlowData> or IQueryable<SpecFlowData> that CreateSet<SpecFlowData>() returns.
var elements = (from item in data
//The two let clauses that where here are unessesary too.
select new MyDataRow {Field = item.Field, Value = item.Value}
).ToList();
return elements;
}
答案 3 :(得分:0)
检查声明类型和linq代码后的结果..
要解决此问题,您可以这样做:
public List<String> GetInputMessage(Table table)
{
var elements = new List<List<string>>();
var data = table.CreateSet<SpecFlowData>().ToList();
elements.AddRange(from item in data
let field = item.Field
let value = item.Value
select new List<string>(new string[] { field ,value}));
return elements.SelectMany(a => a).ToList();
}
但还有其他方法可以解决您的问题...