How to search in 2D array by LINQ ?[version2]

前端 未结 2 1247
迷失自我
迷失自我 2020-12-10 14:02

I have an 2D array like this:

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


        
2条回答
  •  再見小時候
    2020-12-10 14:43

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

    Something like this would work:

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

    Or in query syntax:

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

    Or perhaps convert the array to a Dictionary first:

    Dictionary 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.

提交回复
热议问题