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

前端 未结 2 1249
迷失自我
迷失自我 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:20

    Here you are:

    color = ClassNames.Cast()
                      .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 or Dictionary instead of string[,].

提交回复
热议问题