Linq to add outer list index to inner elements
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 inne开发者_运维百科r list ?
var result = outer.SelectMany((inner, index) => inner.Select(item => Tuple.Create(item, index)));
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}));
精彩评论