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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…