Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effective way in LINQ of joining based on index

Tags:

c#

linq

I have written code that works, but I can't seem to find a better way to combine the lists together if they have the same index.

    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};

(When I say combine, I don't mean append to the end of the list. {{a,b},{a,b}, .... { }}: Maybe I have the terminology wrong when trying to research.)

like image 999
Mikes3ds Avatar asked Apr 11 '16 15:04

Mikes3ds


2 Answers

You can use Enumerable.Zip:

var combine = apples.Zip(carrots, (a, c) => new { Apple = a, Carrot = c});
like image 74
Tim Schmelter Avatar answered Oct 19 '22 06:10

Tim Schmelter


apples.Select((a,i)=> new { Apple = a, Carrot = carrots[i] });

That should work too.

like image 5
AD.Net Avatar answered Oct 19 '22 07:10

AD.Net