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

11,324

Solution 1

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

Solution 2

Here you are:

color = ClassNames.Cast<string>()
                  .Select((x, i) => new { x, i })
                  .GroupBy(x => x.i / 2, (k,x) => x.Select(y => y.x))
                  .Where(g => g.First() == className)
                  .Select(x => x.Last()).First();

But to be honest, I would never use LINQ to do that. It's less efficient, less readable and worse to maintain. You should consider using your existing for loops or change your data structure, to be List<CustomClass> or Dictionary<string, string> instead of string[,].

Share:
11,324

Related videos on Youtube

Samiey Mehdi
Author by

Samiey Mehdi

I am a web developer with C# and ASP.NET.

Updated on June 17, 2022

Comments

  • Samiey Mehdi
    Samiey Mehdi almost 2 years

    I have an 2D array like this:

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

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

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

    • myermian
      myermian over 10 years
      Your 2D array looks like it should be a dictionary instead?
  • p.s.w.g
    p.s.w.g over 10 years
    @SamieyMehdi That's the null coalescing operator. It basically means 'if the value to the left is null, use the value to the right instead'. Note that this only works for reference or nullable types. If your actual array is a int[,], you'll have to cast the result to a (int?) in the select clause to get that to work.
  • MarcinJuraszek
    MarcinJuraszek over 10 years
    You'll get that error when there is no element matching. I've tested it with your sample input and returned "Red".