Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of how this lambda expression in plain English?

Tags:

c#

lambda

linq

I converted a query syntax Select example from MSDN into Lambda. It works, and I have written it myself but I can't get my head around the commented line below. I mean, I am selecting from numbers array, and yet it works fine and instead of digits shows equivalent strings . How does it match the two arrays?

  int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  string[] strings = {"zero", "one", "two", "three", "four",
                       "five", "six", "seven", "eight", "nine" }; 

  //Confusing line: **How would we represent this line below in plain english?**
  var result = numbers.Select(d => strings[d]);
  foreach (var d in result)

  {
   Console.WriteLine(d); 
  }

Output:

five 
four
one 
..rest of numbers follow

Original MSDN Code in Query syntax:

var result= 
        from n in numbers 
        select strings[n];       

    foreach (var s in strings) 
    { 
        Console.WriteLine(s); 
    } 

Maybe explaining such a thing is a bit tricky, but I'm hoping someone has just the right words so it makes sense :)

Thank you

like image 879
iAteABug_And_iLiked_it Avatar asked Dec 15 '22 07:12

iAteABug_And_iLiked_it


1 Answers

Look at .Select() as "create an IEnumerable of whatever comes after the =>."

As a foreach, it would look like:

var result = new List<string>();
foreach(var d in numbers)
{
    result.Add(strings[d]);
}
return result;
like image 166
Khan Avatar answered Dec 18 '22 12:12

Khan