Comparison of Take, TakeWhile, Skip, and SkipWhile in Linq (convert), takewhileskipwhile
Reference: http://blog.csdn.net/lxfzgg/article/details/20534281
Take ()
Int [] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; var first3Numbers = numbers. take (3); // starting from the first element, the previous number Console is used to obtain the three return statements. writeLine ("First 3 numbers:"); foreach (var n in first3Numbers) {Console. writeLine (n); // result 5 4 1}
TakeWhile ()
Int [] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; // note here. use TakeWhile to get the element smaller than 6, starting from the first element, // until it does not meet the condition smaller than 6. that is to say, after the comparison is executed to the element 9, the comparison is over. // you can imagine the execution process. // 5 <6 = true; 4 <6 = true; 1 <6 = true; 3 <6 = true/9 <6 = false; the comparison of var firstNumbersLessThan6 = numbers is stopped. takeWhile (n => n <6); Console. writeLine ("First numbers less than 6:"); foreach (var n in firstNumbersLessThan6) {Console. writeLine (n); // The result is 5 4 1 3}
Skip ()
Int [] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; var allButFirst4Numbers = numbers. skip (4); // Skip the first four elements to obtain the Console of all elements. writeLine ("All but first 4 numbers:"); foreach (var n in allButFirst4Numbers) {Console. writeLine (n); // result 9 8 6 7 2 0}
SkipWhile ()
Int [] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // skip all elements that cannot be divisible by 3 // here is different from TakeWhiel. // When TakeWhile encounters a condition that is not met, return will be returned. // However, if SkipWhile is executed, then the elements after it will not continue to be compared // Similarly, imagine the execution process // 5% 3! = 0 = true; 4% 3! = 0 = true; 1% 3! = 0 = true; // 3% 3! = 0 = false; when running here, the following will not be compared. // The output result contains the following elements: 8, 7, 2, and 0: var allButFirst3Numbers = numbers. skipWhile (n => n % 3! = 0); foreach (var n in allButFirst3Numbers) {Console. WriteLine (n); // result 3 9 8 6 7 2 0}