Join 2 lists by order instead of condition in LINQ

2019-04-09 01:53发布

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".

3条回答
别忘想泡老子
2楼-- · 2019-04-09 02:18

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.

查看更多
疯言疯语
3楼-- · 2019-04-09 02:19

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]}); 
查看更多
beautiful°
4楼-- · 2019-04-09 02:33

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});
查看更多
登录 后发表回答