0

I have a collection:
[ A { 'a' => '1', 'b' => ['1', '2']}
B { 'a' => '2', 'b' => ['1','2','3']} ]

I'm searching for a function to 'duplicate' items in this collection to make next result:
[ A1 { 'a' => '1', 'b' => '1'}
A2 { 'a' => '1', 'b' => '2'}
B1 { 'a' => '2', 'b' => '1'}
B2 { 'a' => '2', 'b' => '2'}
B3 { 'a' => '2', 'b' => '3'} ]

How can i achive such result?

Dima
  • 6,721
  • 4
  • 24
  • 43

1 Answers1

1

Not very clear about your definition of class A/B. I suppose your class looks like:

class Data
{
    public int a;
    public int[] b;
}

And prepare the data like:

var A = new Data { a = 1, b = new[] { 1, 2, } };
var B = new Data { a = 2, b = new[] { 1, 2, 3 } };
List<Data> original = new List<Data> { A, B };

Using .SelectMany to flatten the data:

var result = original.SelectMany(item => 
                          item.b.Select(x => 
                             new { a = item.a, b = x }))
                     .ToList();

Please ignore some bad programming habits in the code(like public fields), and feel free to suggest the coding-style of the last linq query.

Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
  • SelectMany definitely can do the trick. There is another overload which looks nicer for that purpose for my taste original.SelectMany(x => x.b, (x, b) => new {a = x.a, b = b}) – Dima Apr 16 '12 at 09:12