user9932489
user9932489

Reputation:

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. But I am looking for a simpler and sorter solution using the 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.

Upvotes: 1

Views: 203

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

Try SelectMany in order to flatten the initial collection:

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 

Upvotes: 7

Related Questions