tags:

views:

43

answers:

2

Let's say I have a list of lists

{ { 'a', 'b', 'c'}, {'d', 'e', 'f'} }

How can I project these to a flat list of the form:

{ {'a', 0}, {'b', 0}, {'c', 0}, {'d', 1}, {'e', 1}, {'f', 1}}

where the 2nd field of each resulting element is the index of the inner list ?

+2  A: 
var result = outer.SelectMany((inner, index) => inner.Select(item => Tuple.Create(item, index)));
dtb
With your using Tuple, this would only work for .NET >= 4
Cristi Diaconescu
You can easily replace the tuple with your own custom class or an anonymous type. The solution is the same.
dtb
A: 

Figured it out...

var input = new []{ new []{'a', 'b', 'c'}, new []{'d', 'e', 'f'}};

var rez = input
    .Select((list, listIdx) => new {list, listIdx})
    .SelectMany(listAndIdx => listAndIdx.list
        .Select(elem => new {elem, listAndIdx.listIdx}));
Cristi Diaconescu