Search code examples
c#linqlambda

Explanation of how this lambda expression in plain English?


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


Solution

  • 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;