我有:
List<int> keys; //These lists are the same size
List<int> reportKeys; //These lists are the same size
int reportType;
我想创建一个新的MyType列表:
List<MyType>
public class MyType
{
public int Key {get;set;}
public int ReportKey {get;set;}
public int ReportType {get;set;}
}
我可以使用for循环来分配这些:
var objects = new List<MyObject>();
for (var i = 0; i < keys.Count(); i++)
{
objects.Add(new MyObject { Key = keys[i], ReportKey = reportKeys[i], ReportType = reportType };
}
有没有办法用linq做这个,而不是使用for循环?
答案 0 :(得分:7)
尝试使用Linq的Zip
扩展方法:
var objects = keys.Zip(reportKeys, (key, reportKey) => new MyType
{
Key = key,
ReportKey = reportKey,
ReportType = reportType
}).ToList();
答案 1 :(得分:1)
您可以使用LINQ Zip
(refer)
以下示例:
var result = keys.Zip(reportsKey,
(key, reportKey) => new MyObject
{
Key = key,
ReportKey = reportKey,
ReportType = reportType
})
.ToList();