我有结构:
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}
因此,result元素的第一个属性必须表示基本元素的全局索引,第二个属性必须表示该元素所属的组的索引.
示例:第3组的第2个元素将投影到{8,3}:
8 - 基本元素的全局索引
3 - 组基元素的索引属于.
您可以通过使用包含索引的Select和版本来做到这一点。SelectMany
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) + "}")));
Run Code Online (Sandbox Code Playgroud)
输出
{1,1}、{2,1}、{3,2}、{4,2}、{5,2}、{6,2}、{7,3}、{8,3}、{9 ,3}