Question

I have this Jagged Array :

(n is given at compile time , so please assume that all values are already there)

int[][] jagged = new int[n][];

jagged[0] = new int[3];
jagged[0][0] = 2; // Please ignore the dummy values....
jagged[0][1] = 55;
jagged[0][2] = 4;

jagged[1] = new int[3];
jagged[1][0] = 6;
jagged[1][1] = 3;
jagged[1][2] = 7;

...
...
jagged[n] = new int[3];
jagged[n][0] = 9;
jagged[n][1] = 5;
jagged[n][2] = 1;

I want to create a IEnumerable<KeyValuePair<int,int>> from this structure where :

key is : dummy value and the value is the n ( dummy value is unique)

(aside info - I need to map pictures to users)

So for group #1 I want:

  {2-> 0}
  {55-> 0}
  {4-> 0}

for group #2

  {6 -> 1}
  {3-> 1}
  {7-> 1}
  ...
  ...
  etc

But as a whole list :

So final result should be 1 IEnumerable of KeyValuePair<int,int>:

  {2-> 0}
  {55-> 0}
  {4-> 0}
  {6 -> 1}
  {3-> 1}
  {7-> 1}
  ...
  {9 -> n}
  {5-> n}
  {1-> n}

Question :

  • Is there any Linq'y way of doing it ?(instead of loops over loops ) ?
Was it helpful?

Solution

foreach (var t in jagged.SelectMany((row, rowIndex) => row.Select(value => new KeyValuePair<int, int>(value, rowIndex))))
{
    Console.WriteLine("{0} - {1}", t.Key, t.Value);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top