Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq with 2D array, Select not found

Tags:

I want to use Linq to query a 2D array but I get an error:

Could not find an implementation of the query pattern for source type 'SimpleGame.ILandscape[,]'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?

Code is following:

var doors = from landscape in this.map select landscape; 

I've checked that I included the reference System.Core and using System.Linq.

Could anyone give some possible causes?

like image 317
LLS Avatar asked Jun 30 '10 15:06

LLS


2 Answers

In order to use your multidimensional array with LINQ, you simply need to convert it to IEnumerable<T>. It's simple enough, here are two example options for querying

int[,] array = { { 1, 2 }, { 3, 4 } };  var query = from int item in array             where item % 2 == 0             select item;  var query2 = from item in array.Cast<int>()                 where item % 2 == 0                 select item; 

Each syntax will convert the 2D array into an IEnumerable<T> (because you say int item in one from clause or array.Cast<int>() in the other). You can then filter, select, or perform whatever projection you wish using LINQ methods.

like image 179
Anthony Pegram Avatar answered Oct 05 '22 13:10

Anthony Pegram


Your map is a multidimensional array--these do not support LINQ query operations (see more Why do C# Multidimensional arrays not implement IEnumerable<T>?)

You'll need to either flatten the storage for your array (probably the best way to go for many reasons) or write some custom enumeration code for it:

public IEnumerable<T> Flatten<T>(T[,] map) {   for (int row = 0; row < map.GetLength(0); row++) {     for (int col = 0; col < map.GetLength(1); col++) {       yield return map[row,col];     }   } } 
like image 26
Ron Warholic Avatar answered Oct 05 '22 13:10

Ron Warholic