tags:

views:

53

answers:

2

I declared a 3 X 3 Matrix

int[,] matrix=new int[3,3]
                {
                   {1,2,3},
                   {4,5,6},
                   {11,34,56}
                };

when i try to enumerate it like

var diagonal = matrix.AsQueryable().Select();

I am unbale to convert it as enumerable collection.How to do that?

+7  A: 

Rectangular arrays don't implement the generic IEnumerable<T> type, so you'll need a call to Cast<>. For example:

using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
    static void Main()
    {
        int[,] matrix=new int[3,3]
                {
                   {1,2,3},
                   {4,5,6},
                   {11,34,56}
                };

        IEnumerable<int> values = matrix.Cast<int>()
                                        .Select(x => x * x);
        foreach (int x in values)
        {
            Console.WriteLine(x);
        }
    }
}

Output:

1
4
9
16
25
36
121
1156
3136
Jon Skeet
Thank you very much Jon
amit
+1  A: 

AsQueryable() is meaningless when applied to array. Select doesn't have overloads without parameters.

matrix (multidimensional array) is IEnumerable itself. If you want to query it, you need to cast it to IEnumerable<int> using matrix.Cast<int>(), it will produce sequence of 1, 2, 3, 4, 5, 6, 11 ...

If you want to get diagonal in Linqish way you should do:

var diagonal = Enumerable.Range(0, matrix.GetLength(0)).Select(i => matrix[i, i]);
Andrey