如何使用linq分配两个列表和一个int来创建一个新对象的列表?

时间:2014-07-28 18:57:20

标签: c# linq

我有:

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循环?

2 个答案:

答案 0 :(得分:7)

尝试使用Linq的Zip扩展方法:

var objects = keys.Zip(reportKeys, (key, reportKey) => new MyType
    {
        Key = key,
        ReportKey = reportKey,
        ReportType = reportType
    }).ToList();

答案 1 :(得分:1)

您可以使用LINQ Ziprefer

以下示例:

var result = keys.Zip(reportsKey, 
                     (key, reportKey) => new MyObject 
                                                { 
                                                    Key = key, 
                                                    ReportKey = reportKey, 
                                                    ReportType = reportType 
                                                 })
                 .ToList();