LINQ where vs takewhile

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

Where can examine the whole sequence looking for matches.

Enumerable.Range(1, 10).Where(x => x % 2 == 1)
// 1, 3, 5, 7, 9

TakeWhile stops looking when it encounters the first non-match.

Enumerable.Range(1, 10).TakeWhile(x => x % 2 == 1)
// 1

Say you have an array that contains [1, 3, 5, 7, 9, 0, 2, 4, 6, 8]. Now:

var whereTest = array.Where(i => i <= 5); will return [1, 3, 5, 0, 2, 4].

var whileTest = array.TakeWhile(i => i <= 5); will return [1, 3, 5].


MSDN says

Enumerable.TakeWhile Method

Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.

Enumerable.Where

Filters a sequence of values based on a predicate.

The difference is that Enumerable.TakeWhile skips the remaining elements from the first non-match whether they match the condition or not