Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join 2 lists by order instead of condition in LINQ

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

like image 565
Ryan Avatar asked Apr 23 '09 23:04

Ryan


2 Answers

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]}); 
like image 107
Christian C. Salvadó Avatar answered Sep 22 '22 00:09

Christian C. Salvadó


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});
like image 33
Matt Ellen Avatar answered Sep 20 '22 00:09

Matt Ellen