Anda di halaman 1dari 2

Differences between Take() and TakeWhile() extension methods in LINQ S.No 1 Take() Meaning: The Take (int...

) method of System.Linq.Queryable class returns the portion of a source i.e. an IEnumerable collection of a source with the first n number of items from the source. Signature of Take (): http://www.csharpcorner.com/UploadFile/d bd951/how-to-usetaketakewhile-andskipskipwhile-inlinq/Images/Linq1.gif TakeWhile() Meaning: 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. Signature of TakeWhile (): http://www.csharpcorner.com/UploadFile/dbd95 1/how-to-use-taketakewhile-andskipskipwhile-inlinq/Images/Linq2.gif Another signature for overriding the method: http://www.csharpcorner.com/UploadFile/dbd95 1/how-to-use-taketakewhile-andskipskipwhile-inlinq/Images/Linq3.gif

Example for Take() extension method: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var firstNumbersLessThan6 = numbers.Take(5); In the above example the Take method returns an IEnumerable collection with only the first 5 items as we have specified in the Take argument. I.e. it will return 5, 4, 1, 3 and 9 only. Examples for TakeWhile() extension method: Example I: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 9); In the above example the TakeWhile will return the collection of items when the condition fails. i.e. if the control reaches the item 9 then the condition fails here so it will return the items from 5 to 3 [5, 4, 1, 3]. Quick Note:

Even though the collection has the items which are less than 9 such as 8,6,7,2,and 0 but it returned only 5,4,1 and 3. The point here is the TakeWhile won't consider the items which are the item which makes the condition fail. Example II: String colection = { "one", "two", "three", "four", "five" }; var strings = collection.TakeWhile(n => n.Length < 4); In this example, the TakeWhile will return the string collection having a length of 4 characters i.e. it will return only the "one" and "two" because the length of the "three" is 5 so it fails there. Example III: String colection = { "one", "two", "three", "four", "five" }; var strings = collection.TakeWhile((s, index)=> s.Length > index ); In this example the TakeWhile will return the items starting from the beginning of the array until a string length is greater than it's position in the collection. So this example will return "one" and "two". Because the "three" has the length of 5 and its position [index] is 2. Since 2 is less than 5 the condition fails at "three". Reference: http://www.c-sharpcorner.com/uploadfile/dbd951/how-to-use-taketakewhile-andskipskipwhile-in-linq/ And, further updates on difference between questions and answers, please visit my blog @ http://onlydifferencefaqs.blogspot.in/

Anda mungkin juga menyukai