我有一个数组列表:
var inp = new List<int[]>()
{
new int[]{11,12,13},
new int[]{21,22,23},
new int[]{31,32,33},
new int[]{41,42,43},
new int[]{51,52,53},
};
Run Code Online (Sandbox Code Playgroud)
我想把它转换成一对列表.我可以使用基本for循环以某种方式完成此操作.但我正在寻找使用LINQ的更简单的分拣机解决方案.
这是我到目前为止:
var outp = new List<KeyValuePair<int, int>>();
var rowlen = inp[0].Length;
for (int i = 0; i < inp.Count; i++)
for (int j = 0; j < rowlen; j++)
outp.Add(new KeyValuePair<int, int>(i * rowlen + j, inp[i][j]));
Run Code Online (Sandbox Code Playgroud)
期望的输出如下所示:
0 11
1 12
2 13
3 21
4 22
5 23
6 31
7 32
8 33
9 41
10 42
11 43
12 51
13 52
14 53
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激.
尝试使用SelectMany来展平初始集合:
var result = inp
.SelectMany(item => item) // Flatten
// .Skip(1) // <- if you want to skip 1st item - 11
.Select((item, index) => new KeyValuePair<int, int>( // Selected as KeyValue
index + 1, // + 1 if you want to start from 1
item))
.ToList(); // Materialized as List
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |