Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...