本文介绍了如何通过 LINQ 在二维数组中搜索?[version2]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 2D 数组:

I have an 2D array like this:

string[,] ClassNames =
{
  {"A","Red"},
  {"B","Blue"},
  {"C","Pink"},
  {"D","Green"},
  {"X","Black"},
};

我通过 for 语句在 1nd 列中搜索 ClassName 并在 2nd 中返回 ColorNamestrong> 像这样的列:

i search ClassName in 1nd column by for statement and return ColorName in 2nd column like this:

string className = "A";
string color = "Black";
for (int i = 0; i <= ClassNames.GetUpperBound(0); i++)
{
   if (ClassNames[i, 0] == className)
   {
      color = ClassNames[i, 1];
      Response.Write(color);
      break;
   }
}

我想使用 LINQ 而不是 for 语句来通过 className 获取颜色.如何将上面的 for 语句转换为 LINQ.

i want use LINQ instead of for statement to get the color by className.how to convert above for statement to LINQ.

推荐答案

您可以使用 Enumerable.Range 方法生成整数序列,然后使用 Linq 查询.

You can do use the Enumerable.Range method to generate a sequence of integers, and then use Linq to query over that.

这样的事情会起作用:

string color = Enumerable
    .Range(0, ClassNames.GetLength(0))
    .Where(i => ClassNames[i, 0] == className)
    .Select(i => ClassNames[i, 1])
    .FirstOrDefault() ?? "Black"; 

或者在查询语法中:

string color = 
    (from i in Enumerable.Range(0, ClassNames.GetLength(0))
     where ClassNames[i, 0] == className
     select ClassNames[i, 1])
    .FirstOrDefault() ?? "Black"; 

或者将数组转换为 Dictionary 先:

Or perhaps convert the array to a Dictionary<string, string> first:

Dictionary<string, string> ClassNamesDict = Enumerable
    .Range(0, ClassNames.GetLength(0))
    .ToDictionary(i => ClassNames[i, 0], i => ClassNames[i, 1]);

然后您可以更轻松地查询它:

And then you can query it much more easily:

color = ClassNamesDict.ContainsKey(className) 
      ? ClassNamesDict[className] 
      : "Black"; 

如果你必须做很多这样的查询,首先生成字典然后查询它会更有效率.

Generating the dictionary first and then querying it will be far more efficient if you have to do a lot of queries like this.

这篇关于如何通过 LINQ 在二维数组中搜索?[version2]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 09:36