Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 基于索引的LINQ连接的有效方法_C#_Linq - Fatal编程技术网

C# 基于索引的LINQ连接的有效方法

C# 基于索引的LINQ连接的有效方法,c#,linq,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

我已经编写了有效的代码,但是如果列表具有相同的索引,我似乎找不到更好的方法将它们组合在一起

    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};
classapple{};
类胡萝卜{};
var apples=新列表();
var carrot=新列表();
var combine=来自苹果中的a
胡萝卜中的c
其中apples.IndexOf(a)=carrots.IndexOf(c)
选择新的{a,c};

(当我说combine时,我并不是说在列表的末尾追加。{{a,b},{a,b},{}:{}也许我在尝试研究时用错了术语。)

你可以使用
Enumerable.Zip

var combine = apples.Zip(carrots, (a, c) => new { Apple = a, Carrot = c});

这也应该行得通

其中apples.IndexOf(a)=carrots.IndexOf(c)-条件缺失否,op只想根据它们的索引获得一对。Zip会自动执行此操作。如果苹果数组的元素比胡萝卜数组的元素多,则会抛出此操作。
apples.Select((a,i)=> new { Apple = a, Carrot = carrots[i] });