c# - 在多维数组中查找值并返回所有项目 c#

标签 c# .net arrays

这里是问题所在,我有一个如下定义的数组:

int[,] Users = new int[1000,3];

它的数据会是这样的:

  • 0,1,2
  • 1,2,1
  • 2,3,2
  • 3,3,4
  • 4,2,3 ...

我的脚本根据需要使用该数组。但我需要能够根据其维度之一过滤数组,并返回所有可用的匹配项。

例如,过滤维度 [1],希望所有匹配 '3' 将返回一个包含以下内容的数组:

  • 2,3,2
  • 3,3,4

谁能帮我解决这个问题?

非常感谢。

最佳答案

如果您可以将数组从 int[,] 更改为 int[][],那么您可以使用 LINQ 轻松实现此目的。

  int[][] users = new int[][]
  {
    new int[]{0,1,2},
    new int[]{1,2,1},
    new int[]{2,3,2},
    new int[]{3,3,4},
    new int[]{4,2,3}
  };


  var result = from u in users 
               where u[1] == 3 
               select u;

如果更改数组不是一个选项,那么您可以编写一个 Filter 函数,如下所示。

public static IEnumerable<T[]> Filter<T>(T[,] source, Func<T[], bool> predicate)
{
  for (int i = 0; i < source.GetLength(0); ++i)
  {
    T[] values = new T[source.GetLength(1)];
    for (int j = 0; j < values.Length; ++j)
    {
      values[j] = source[i, j];
    }
    if (predicate(values))
    {
      yield return values;
    }
  }      
}

然后可以如下调用上面的内容

var result = Filter(users, u => u[1] == 3);

您可以更进一步,为 Where 函数实现您自己的自定义 Linq 扩展,这将允许您过滤 T[,] 数组。这是一个可以帮助您入门的简单示例。

public static class LinqExtensions
{
  public static IEnumerable<T[]> Where<T>(this T[,] source, Func<T[], bool> predicate)
  {
    if (source == null) throw new ArgumentNullException("source");
    if (predicate == null) throw new ArgumentNullException("predicate");
    return WhereImpl(source, predicate);
  }

  private static IEnumerable<T[]> WhereImpl<T>(this T[,] source, Func<T[], bool> predicate)
  {      
    for (int i = 0; i < source.GetLength(0); ++i)
    {
      T[] values = new T[source.GetLength(1)];
      for (int j = 0; j < values.Length; ++j)
      {
        values[j] = source[i, j];
      }
      if (predicate(values))
      {
        yield return values;
      } 
    }
  }    
}

这样你就可以像第一个例子一样再次使用 Linq 来过滤数组

  var result = from u in users 
               where u[1] == 3 
               select u;

关于c# - 在多维数组中查找值并返回所有项目 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5612456/

相关文章:

c# - .NET Framework 如何分配线程 ID?

c# - 将 bool 映射到 LINQ to SQL 数据源中的 'Y'/'N' 字段

.net - 在 .net 中绘制科学数据

.net - 如何将 Binding.Path 属性绑定(bind)到基础数据?

javascript - 如何使用JavaScript获取json数据中数组的名称

c# - 在 .Net Core Web API 中使用 web.config 文件

c# - 将 bool 值绑定(bind)到 visualstate

c# - 在命令行使用 aspnet_compiler 抑制编译器警告

arrays - perl6 : passing an Array of UInt fails, 而 Int 数组成功

mysql - 查找字符串包含关键字的位置