Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ unable to enumerate matrix

Tags:

c#

asp.net

linq

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?

like image 877
amit Avatar asked Jan 21 '23 12:01

amit


1 Answers

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
like image 139
Jon Skeet Avatar answered Jan 28 '23 05:01

Jon Skeet