Using Linq with 2D array, Select not found

前端 未结 2 793
天命终不由人
天命终不由人 2020-11-27 20:39

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.ILandsca

相关标签:
2条回答
  • 2020-11-27 21:25

    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.

    0 讨论(0)
  • 2020-11-27 21:40

    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];
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题