简体   繁体   English

使用 LINQ 将数组列表转换为 KeyValuePairs 列表

[英]Convert List of array into the list of KeyValuePairs using LINQ

I have a list of arrays:我有一个数组列表:

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

And I would like to convert it into list of a pairs.我想将其转换为成对列表。 I can accomplish this somehow using basic for loops.我可以使用基本的 for 循环以某种方式完成此操作。 But I am looking for a simpler and sorter solution using the LINQ.但我正在寻找使用 LINQ 的更简单的分类解决方案。

This is what I have so far:这是我到目前为止:

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

Desired output looks like this:所需的输出如下所示:

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

Any help would be appreciated.任何帮助,将不胜感激。

Try SelectMany in order to flatten the initial collection:尝试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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM