如何使用LINQ从多个序列投影?

时间:2015-01-13 10:54:43

标签: c# linq

所有

我有三个系列:

{"Alex", "Anna"}
{19, 20}
{"A", "B"}

我想将它们全部投射到一个类型为&#34的对象序列中;学生"使用LINQ和以下lambda或其他东西:

(name, age, grade)=>new Student(name, age, grade)

结果应该是两个学生对象(" Alex",19," A")和(" Anna",20," B&#34 ;)

我该怎么做?

2 个答案:

答案 0 :(得分:5)

您可以合并两个Zip来实现此目的:

names.Zip(ages, (n,a) => new { name = n, age = a })
     .Zip(grades, (s,g) => new Student { Name = s.name, Age = s.age, Grade = g });

答案 1 :(得分:2)

我会使用Zip

var names = new[] {"Alex", "Anna"};
var ages = new[] {19, 20}
var grades = new[] {"A", "B"}


var students = names.Zip(ages, (n, a) => Tuple.Create(n, a))
                    .Zip(grades, (t, g) => new Student(t.Item1, t.Item2, g));