Join 2 lists by order instead of condition in LINQ

一个人想着一个人 提交于 2020-01-01 10:28:19

问题


How can I join 2 lists of equal lengths (to produce a 3rd list of equal length) where I do not want to specify a condition but simply rely on the order of items in the 2 lists.

Eg how can I join:

{1,2,3,4} with {5,6,7,8}

to produce:

{{1,5}, {2,6}, {3,7}, {4,8}}

I have tried the following:

from i in new []{1,2,3,4}
from j in new []{5,6,7,8}
select new { i, j }

but this produces a cross join. When I use join, I always need to specify the "on".


回答1:


You could use Select in the first list, use the item index and access the element on the second list:

var a = new [] {1,2,3,4};
var b = new [] {5,6,7,8};

var qry = a.Select((i, index) => new {i, j = b[index]}); 



回答2:


If you are using .Net 4.0, you can use the Zip extension method and Tuples.

var a = new [] {1,2,3,4};
var b = new [] {5,6,7,8};

var result = a.Zip(b, (an, bn) => Tuple.Create(an, bn));

Alternatively, you can keep them as arrays:

var resultArr = a.Zip(b, (an, bn) => new []{an, bn});



回答3:


There is a half way solution, if you want to use query syntax. Half way in the sense that you need to use the Select method on both lists in order to get the indexes that you will use in the where clause.

int[] list1 = {1,2,3,4};
int[] list2 = {5,6,7,8};

var result = from item1 in list1.Select((value, index) => new {value, index})
             from item2 in list2.Select((value, index) => new {value, index})
             where item1.index == item2.index
             select new {Value1 = item1.value, Value2 = item2.value};

The benefit with this solution is that it wont fail if the lists have different lengths, as the solution using the indexer would do.



来源:https://stackoverflow.com/questions/783922/join-2-lists-by-order-instead-of-condition-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!