基于索引的LINQ加入的有效方法

Mik*_*3ds 14 c# linq

我编写了可行的代码,但如果它们具有相同的索引,我似乎无法找到将列表组合在一起的更好方法.

    class Apple {};
    class Carrot {};

    var apples = new list<Apple>();
    var carrot = new list<Carrot>();

    var combine = from a in apples
                  from c in carrots
                  where apples.IndexOf(a) == carrots.IndexOf(c)
                  select new {a, c};
Run Code Online (Sandbox Code Playgroud)

(当我说组合时,我的意思并不是追加到列表的末尾.{{a,b},{a,b},.... {}}:在尝试研究时,我的术语可能不对.)

Tim*_*ter 21

你可以使用Enumerable.Zip:

var combine = apples.Zip(carrots, (a, c) => new { Apple = a, Carrot = c});
Run Code Online (Sandbox Code Playgroud)

  • 不,只是想根据他们的指数获得一对.Zip自动完成 (7认同)

AD.*_*Net 5

apples.Select((a,i)=> new { Apple = a, Carrot = carrots[i] });
Run Code Online (Sandbox Code Playgroud)

那也应该有效。

  • 如果苹果数组的元素多于胡萝卜数组,则会抛出此错误。 (3认同)