将 Linq 与 2D 数组一起使用,未找到选择

发布于 2024-09-07 20:23:53 字数 379 浏览 0 评论 0原文

我想使用 Linq 查询 2D 数组,但出现错误:

找不到源类型“SimpleGame.ILandscape[,]”的查询模式的实现。 未找到“选择”。您是否缺少对“System.Core.dll”的引用或“System.Linq”的 using 指令?

代码如下:

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

我已检查是否包含引用 System.Core 并使用 System.Linq

谁能给出一些可能的原因吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷迭香的记忆 2024-09-14 20:23:54

您的地图是多维数组 - 这些不支持 LINQ 查询操作(请参阅更多为什么 C# 多维数组不实现 IEnumerable

您需要扁平化数组的存储(出于多种原因,这可能是最好的方法)或为其编写一些自定义枚举代码:

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];
    }
  }
}

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];
    }
  }
}
浅沫记忆 2024-09-14 20:23:53

为了在 LINQ 中使用多维数组,您只需将其转换为 IEnumerable。这很简单,这里有两个用于查询的示例选项

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 (因为您在一个 from 子句中说 int item 或 < code>array.Cast() 中的另一个)。然后,您可以使用 LINQ 方法过滤、选择或执行您想要的任何投影。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文