Linq将外部列表索引添加到内部元素

时间:2010-08-31 14:09:26

标签: c# .net linq

假设我有一份清单

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

如何将这些投影到表单的平面列表中:

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

其中每个结果元素的第二个字段是内部列表的索引?

2 个答案:

答案 0 :(得分:2)

var result = outer.SelectMany((inner, index) => inner.Select(item => Tuple.Create(item, index)));

答案 1 :(得分:0)

想出来......

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