Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ where vs takewhile

Tags:

.net

linq

I want to get a difference between TakeWhile & Where LINQ methods .I got the following data from MSDN .But It didn't make sense to me

Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)  

Filters a sequence of values based on a predicate.

TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) 

Returns elements from a sequence as long as a specified condition is true.

All opinions are welcomed.

like image 722
Mohammed Thabet Avatar asked Feb 17 '11 16:02

Mohammed Thabet


People also ask

What is difference between Take and TakeWhile in linq?

The Take() extension method returns the specified number of elements starting from the first element. Take & TakeWhile operator is Not Supported in C# query syntax. However, you can use Take/TakeWhile method on query variable or wrap whole query into brackets and then call Take/TakeWhile().

What is TakeWhile Linq?

TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) Returns elements from a sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function.

How to use TakeWhile in linq?

TakeWhile method:The TakeWhile (Func...) will return elements starting from the beginning of an IEnumerable collection until it satisfies the condition specified. If the condition is false then it will return the collection immediately. Example I: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

What is TakeWhile?

takeWhile is a built-in method in Haskell that inspects the original list using a given predicate and returns its elements until the condition is false.


1 Answers

TakeWhile stops when the condition is false, Where continues and find all elements matching the condition

var intList = new int[] { 1, 2, 3, 4, 5, -1, -2 }; Console.WriteLine("Where"); foreach (var i in intList.Where(x => x <= 3))     Console.WriteLine(i); Console.WriteLine("TakeWhile"); foreach (var i in intList.TakeWhile(x => x <= 3))     Console.WriteLine(i); 

Gives

Where 1 2 3 -1 -2 TakeWhile 1 2 3 
like image 180
Albin Sunnanbo Avatar answered Oct 14 '22 14:10

Albin Sunnanbo