LINQ获取全局索引

本文关键字:索引 全局 获取 LINQ | 更新日期: 2023-09-27 18:15:10

我有结构:

List<List<x>> structure = new { {x,x}, {x,x,x,x}, {x,x,x}}

如何使用linq将其投影到以下序列?

{1,1},{2,1},{3,2},{4,2},{5,2},{6,2},{7,3},{8,3},{9,3}

因此结果元素的第一个属性必须表示基本元素的全局索引,第二个属性必须表示该元素所属的组的索引。

示例:第三组的第二个元素将被投影为{8,3}:

8 -基本元素的全局索引

LINQ获取全局索引

您可以通过使用包含索引的SelectSelectMany版本来做到这一点。

IList<IList<int>> structure = new[] 
{ 
    new[] { 1, 1 }, 
    new[] { 1, 1, 1, 1 }, 
    new[] { 1, 1, 1 } 
};
var result = structure.SelectMany((l, i) => l.Select(v => i))
    .Select((i, j) => new[] {j + 1, i + 1});
Console.WriteLine(string.Join(",", result.Select(l => "{" + string.Join(",", l) + "}")));

输出

{1}, {2 1}, {3 2}, {4 2}, {5, 2}, {6 2}, {7, 3}, {8 3}, {9, 3}