After reading this answer https://stackoverflow.com/a/902123 I wanted to check out how LINQ would work on multi-dimensional lists, so here is some test code that I just can not get right.
class Program
{
static void Main(string[] args)
{
// Two dimensional list of ints
var arr = new List<List<int>>();
var rand = new Random();
// fill the array with random values, this works fine.
for (int i=0; i<10; i++)
{
arr.Add(new List<int>());
for (int k=0; k<5; k++)
{
arr[i].Add( rand.Next(1, 21) );
}
}
var q = from int e in arr select e;
List<int> lst = q.ToList(); // This fails with InvalidCastException
// here I would like to pretend that the list is one dimensional
foreach (int i in lst)
{
Console.WriteLine(i);
}
}
The idea is that the list should look like it has only one dimension, after I cast the query back to List< int >.
What might be the cause of the problem:
Visual studio tells me that 'q' has type
{System.Linq.Enumerable.WhereSelectEnumerableIterator< int, int >}
Whereas the answer I linked to at the top of this question states that 'q' should have type
IEnumerable< int >
Question 1: Why is the exception thrown?
Question 2: How can I convert multi-dim list to one dimensional list with LINQ?
Thank you.