English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The partition operator divides a sequence (collection) into two parts and returns one of them.
The Take() extension method returns a specified number of elements starting from the first element.
IList<string> strList = new List<string>(){ "One", "Two", "Three", "Four", "Five" }; var newList = strList.Take(2); foreach(var str in newList) Console.WriteLine(str);
One Two
C# query syntax does not support Take & takedwhile operators. However, you can use Take on the query variable/The takedwhile method, or wrap the entire query in parentheses and then call Take/takedwhile ()
Dim takeResult = From s In studentList Take 3 Select s
The TakeWhile() extension method returns elements from the given collection until the specified condition is true. If the first element itself does not meet the condition, an empty collection is returned.
TakeWhile method has two overloads. One method accepts a predicate of type Func<TSource, bool>, and another overload accepts a predicate of type Func<TSource, int, bool> that passes the element index.
In the following example, the TakeWhile() method returns a new collection containing all elements until an element with a length less than4characters.
Example: The TakeWhile method in C# returns strings whose length is greater than4elements
IList<string> strList = new List<string>(){ "Three", "Four", "Five", "Hundred"}; var result = strList.TakeWhile(s => s.Length > 4); foreach(string str in result) Console.WriteLine(str);
Three
In the above example, TakeWhile() returns only the first element because the second string element does not meet the condition.
TakeWhile also passes the current element's index in the predicate function. The following TakeWhile method example accepts elements until the length of the string element is greater than its index
IList<string> strList = new List<string>(){ "One", "Two", "Three", "Four", "Five", "Six"}; var resultList = strList.TakeWhile((s, i) => s.Length > i); foreach(string str in resultList) Console.WriteLine(str);
One Two Three Four