0

I have the following code. I would like to replace the for loop to a lambda or LINQ expression to return my string.

string[,] testval = new string[3,2]

testval[0, 0] = "0"
testval[0, 1] = "string A"
testval[1, 0] = "5"
testval[1, 1] = "string B"
testval[2, 0] = "13"
testval[2, 1] = "string C"

string teststring = "13"

for (int i=0; i<=testval.GetUpperBound(0);i++)
{
    if (testval[i,0] == teststring) { return testval[i,1]; }
}
return null;

I am new to lambda and LINQ expressions. Can somebody help me?

Zong
  • 6,160
  • 5
  • 32
  • 46
ib11
  • 2,530
  • 3
  • 22
  • 55
  • 1
    Rather than using a 2D array and lambda expression, I'd suggest using a `Dictionary` instead. – Dan Harms Apr 27 '16 at 22:28
  • Do you mean "lambda" or do you mean "LINQ"? 'Cause I'm not sure what a lambda would get you here, but a LINQ expression might be an alternate way of doing the work while eliminating the explicit loop. – davidbak Apr 27 '16 at 23:21
  • @davidbak Thanks. Both would work, yes. I just would like to have it simpler than a for loop. – ib11 Apr 28 '16 at 00:02
  • 1
    As long as the keys are unique, a dictionary would be better suited for this. Then you could do `if (testval.ContainsKey(teststring)) return testval[teststring];` – Tim Apr 28 '16 at 00:16
  • Is there maybe a direct command where you don't need to do a loop cycle? – ib11 Apr 29 '16 at 23:34

1 Answers1

2

You can use Enumerable.Range() to generate the sequence of integers you want to iterate over, and then build a Linq query over that:

var result = Enumerable.
                .Range(0, testval.GetUpperBound(0)+1)
                .Where(i => testval[i,0] == teststring)
                .Select(i => testval[i,1])
                .FirstOrDefault();

For using query syntax, or other approaches, look at this excellent answer.

gnalck
  • 972
  • 6
  • 12
  • Great, thank you. So basically you anyway need to loop through them. I wondered if there is another way of doing it without looping. – ib11 Apr 29 '16 at 23:33