发现价值的多维数组并返回C#的所有项目多维、数组、价值、发现

2023-09-04 01:17:42 作者:陌上桑

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

here is the issue, I have an array defined like below:

INT [,]用户=新INT [1000,3];

其数据将是这样的:

在0,1,2 在1,2,1 在2,3,2 在3,3,4 在4,2,3 ... 0,1,2 1,2,1 2,3,2 3,3,4 4,2,3 ...

根据需要通过我的脚本阵列被使用。但我需要能够根据它的维之一来过滤该阵列,并返回所有可用的匹配。

the array is used as needed by my script. but I need to be able to filter the array based on one of its dimensions, and return all available matches.

例如,过滤维度上[1],希望所有的比赛'3' 会返回一个数组,包含:

For example, filtering on dimension [1], wanting all that match '3' will return an array containing:

在2,3,2 在3,3,4

谁能给我一个手呢?

非常感谢。

推荐答案

如果你可以从 INT [,] 改变你的阵列 INT [ ] [] ,那么你可以很容易地使用LINQ实现这一目标。

If you can change your array from int[,] to int[][] then you can easily achieve this using 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;

如果改变你的阵列是不是一种选择,那么你可以写一个过滤器功能如下。

If changing your array is not an option then you could write a Filter function as follows.

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

以上然后可以如下名为

The above could then be called as follows

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

您可以借此更进一步,实现自己的自定义LINQ的扩展名其中,功能,这将允许您筛选 T [, ] 阵列。这里是可以让你开始了一个天真的例子。

You could take this a step further and implement your own custom Linq extension for the Where function which would allow you to filter the T[,] arrays. Here is a naive example that could get you started.

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作为第一个例子来过滤阵列

With this you can again use Linq as in the first example to filter the array

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