15,922,166 members
See more:
Dear all,

I have the following Two Dimensional Array:

C#
`object[,] cellValues`

[1,1] = "x"
[1,2] = "y"
[1,3] = "z"

[2,1] = "a"
[2,2] = "b"
[2,3] = "c"

[3,1] = "i"
[3,2] = "j"
[3,3] = "k"

[4,1] = "p"
[4,2] = "q"
[4,3] = "r"

[5,1] = "m"
[5,2] = "n"
[5,3] = "o"

Now I am trying to transform the above Two Dimensional array into Dictionary or List:

1 [x,y,z]
2 [a,b,c]
3 [i,j,k]
4 [p,q,r]
5 [m,n,o]

How to do this using LINQ as for/foreach is taking long time to complete this?
Please note that, the Two Dimensional array containf 513360 values.

What I have tried:

C#
```var xLimit = Enumerable.Range(0, cellValues.GetUpperBound(0) + 1);
var yLimit = Enumerable.Range(0, cellValues.GetUpperBound(1) + 1);
var result = xLimit.SelectMany(x => yLimit.Select(y => cellValues[x, y]));```
Posted
Updated 7-Oct-16 3:13am

## Solution 1

Linq probably won't speed this up: it doesn't remove the loop it just hides and defers it until you need the results at which point it is evaluated.

Instead, look at using Parallel.For[^] for your outer loop and it will "encourage" your computer to make use of multiple cores. That may significantly reduce the time taken to process it. Or it may make it worse due to the thread setup and switching overhead. In that case, divide your loop into multiple sections (one per core in your target PC) and do it in "chunks" then assemble the chunks when completed.

## Solution 3

You could use AsParallel() method which help to execute line query as parallel.
C#
```var xLimit = Enumerable.Range(0, cellValues.GetUpperBound(0) + 1);
var yLimit = Enumerable.Range(0, cellValues.GetUpperBound(1) + 1);
var result = xLimit.AsParallel().SelectMany(x => yLimit.AsParallel().Select(y => cellValues[x, y]));```

for more detail ; https://msdn.microsoft.com/tr-tr/library/system.linq.parallelenumerable.asparallel(v=vs.110).aspx[^]

## Solution 4

Here's something that might work. Doesn't use LINQ, so it should be faster.

C#
```public class Model
{
public List<string> Values { get; set; }
}

string[,] parts = new string[,] {{"a","b","c"},{"d","e","f"}};
List<Model> list = new List<Model>();

//find out how big our array is
int dim1 = parts.GetLength(0);
int dim2 = parts.GetLength(1);

for (int i = 0; i < dim1; i++)
{
List<string> values = new List<string>();
for (int j = 0; j < dim2; j++)
{
}
list.Add(new Model(){ Values = values });
}```

v3

Top Experts
Last 24hrsThis month
 Ștefan-Mihai MOGA 25 Wendelius 20 Member 10231707 10 Dave Kreskowiak 6 CHill60 5
 Pete O'Hanlon 995 OriginalGriff 916 Dave Kreskowiak 499 Richard Deeming 340 Richard MacCutchan 320

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900