如何将列表<列表<string>>复制到 LINQ 中的类?

  • 本文关键字:列表 LINQ string 复制 linq
  • 更新时间 :
  • 英文 :


我一直在使用嵌套for循环从List<List<string>>中提取数据。

public class CustomerData()
{
public string Id {get; set;};
public string Name {get; set;};
}
var data = new List<CustomerData>();
List<List<string>> result = new List<List<string>>();

如何使用linq将List<List<string>>的内容传输到List<CustomerData>

// this doesn't compile
List<CustomerData> list2 = result.Select(item =>
item.Select(x => new CustomerData
{
Id= x[0],
Name = x[1]
})).ToList();

您有一个不需要的额外选择。你应该寻找:

var rawData = new List<List<string>>
{
new List<string> {"Id A", "Name A"},
new List<string> {"Id B", "Name B"},
new List<string> {"Id C", "Name C"}
};
var results = rawData.Select(grouping => new CustomerData
{
Id = grouping[0], 
Name = grouping[1]
}).ToList();

最新更新