开发者

C# LINQ unable to enumerate matrix

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?


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


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]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜