[英]Using Linq with 2D array, Select not found
我想使用Linq查詢2D數組,但出現錯誤:
找不到源類型為'SimpleGame.ILandscape [ , ]'的查詢模式的實現。 找不到“選擇”。 您是否缺少對“ System.Core.dll”的引用或對“ System.Linq”的using指令?
代碼如下:
var doors = from landscape in this.map select landscape;
我檢查了是否包含參考System.Core
並使用了System.Linq
。
誰能給出一些可能的原因?
為了將多維數組與LINQ一起使用,您只需要將其轉換為IEnumerable<T>
。 這很簡單,這是兩個示例查詢選項
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;
每種語法都會將2D數組轉換為IEnumerable<T>
(因為您在一個from子句或array.Cast<int>()
中說一個int item
)。 然后,您可以使用LINQ方法過濾,選擇或執行所需的任何投影。
您的地圖是多維數組-它們不支持LINQ查詢操作(請參閱更多為什么C#多維數組不實現IEnumerable <T>? )
您將需要為陣列展平存儲(可能出於多種原因可能是最好的方法),或者為此編寫一些自定義枚舉代碼:
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];
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.