Hi,
I am learning Lamda Expressions and I find it hard to understand the below expression. Can some one please explain. I took it from msdn.
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);
As per my understanding the above expression is trying to get all the numbers whose value >= its position. So the output should be(values): 5,4,3,9,8,7 and index(0,1,3,4,5,6,7)
But the original output is 5,4
Appreicate your help.
Thanks.
Aravind
Loading
Manikavelu VelayuthamPosted Jan 11, 2011, 7:01 AM
You have misunderstood the functionality.
From the word itself, you should understand how it works.
TakeWhile --> Take the words Until the condition satisfies.
From your example, its iterating starting from 5.
For 5 --> Condition is true
For 4 --> Condition is true
For 1 --> Condition Fails. So its stop printing after 4. It wont proceed further.
Thats why the output 5, 4
Hope you understood. Let me know if you still need clarification.
Another example for you.
string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };
IEnumerable<string> query =
fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
/*
This code produces the following output:
apple
banana
mango
*/
Here the above program prints the fruit name until it matches the fruit name orange. Its a cool functionality and its more useful in iterations.
You can use it in a situation like, you can do the looping until the condition satisfies. Its just a single line of code. Thats the Functional Programming.
aravind GoshPosted Jan 11, 2011, 1:20 PM
Manikavelu VelayuthamPosted Jan 11, 2011, 7:20 AM
If you change the inputs like
int[] numbers = { 15, 14, 11, 13, 19, 18, 16, 17, 12, 8 };
output will be 15, 14, 11, 13, 19, 18, 16, 17, 12
Here why the 8 is not printed means, 8 >= 9, whereas 8 is the element, 9 is the index of 8. Condition fails here. so it wont print 8