开发者

Linq to add outer list index to inner elements

开发者 https://www.devze.com 2023-01-14 18:58 出处:网络
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:

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

精彩评论

暂无评论...
验证码 换一张
取 消