Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you combine multiple lists with LINQ?

Tags:

c#

.net

linq

Say I have two lists:

var list1 = new int[] {1, 2, 3};
var list2 = new string[] {"a", "b", "c"};

Is it possible to write a LINQ statement that will generate the following list:

var result = new []{ 
    new {i = 1, s = "a"},
    new {i = 1, s = "b"},
    new {i = 1, s = "c"},
    new {i = 2, s = "a"},
    new {i = 2, s = "b"},
    new {i = 2, s = "c"},
    new {i = 3, s = "a"},
    new {i = 3, s = "b"},
    new {i = 3, s = "c"}
};

?

Edit: I forgot to mention I didn't want it in query syntax. Anyway, based on preetsangha's answer I've got the following:

var result = list1.SelectMany(i =>  list2.Select(s => new {i = i, s = s}));
like image 676
Cameron MacFarland Avatar asked Nov 14 '08 05:11

Cameron MacFarland


2 Answers

var result = from l1 in list1
             from l2 in list2       
             select new { i = l1, s = l2};
like image 63
Preet Sangha Avatar answered Oct 20 '22 03:10

Preet Sangha


preetsangha's answer is entirely correct, but if you don't want a query expression then it's:

var result = list1.SelectMany(l1 => list2, (l1, l2) => new { i = l1, s = l2} );

(That's what the compiler compiles the query expression into - they're identical.)

like image 40
Jon Skeet Avatar answered Oct 20 '22 02:10

Jon Skeet