stuart-d2
10/3/2014 - 3:55 PM

Lambda Expression : LE & Array Processing

Lambda Expression : LE & Array Processing

//C# example 
//An array of words setup..  
void Main() {
string[] words = { "cherry", "apple", "blueberry" };
// Use method syntax to apply a lambda expression to each element
// of the words array.
// setup the variable -- int named 'shortestWordLength' 
// Assign to type 'shortestWordLenth' the value.  words is the array, with the min method called on it to get the smallest length, then the lamdba expression. 'w' is going to represent the element. 'w.length' will represent the element within the array's length.  
int shortestWordLength = words.Min(w => w.Length);
Console.WriteLine(shortestWordLength);

// Compare the following code that uses query syntax.
// Get the lengths of each word in the words array.
// setup a variable representing the query.
// w represents the element in the array, prefixed with from keyword.
// in keyword and a reference to the array we want to cycle through.  
// select keyword to select the attribute of the element.  
var query = from w in words
            select w.Length;

// Apply the Min method to execute the query and get the shortest length.
//Setup a output variable of sorts. Assigned the result of the query Min() method.   
int shortestWordLength2 = query.Min();
//Output the output variable to the console.
Console.WriteLine(shortestWordLength2);
// Output: 
// 5
// 5

}

//See also the String Class method options -- http://msdn.microsoft.com/en-us/library/system.string_methods(v=vs.110).aspx