Csharp/C Sharp/LINQ/TakeWhile

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

TakeWhile with condition

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass{
public static void Main() {
            int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            
            var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);
            
            Console.WriteLine("First numbers less than 6:");
            foreach (var n in firstNumbersLessThan6) {
                Console.WriteLine(n);
            }
        }
}


TakeWhile with expresion

 
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"1234567890123", "Art", "Buch", "Bush", "Car", "land"};
        IEnumerable<string> items = presidents.TakeWhile(s => s.Length < 10);
        foreach (string item in items)
            Console.WriteLine(item);
    }
}


TakeWhile with two parameters

 
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"ant", "Hard", "Harrison", "Hayes", "Hoover", "Jack"};
        IEnumerable<string> items = presidents
         .TakeWhile((s, i) => s.Length < 10 && i < 5);
        foreach (string item in items)
            Console.WriteLine(item);
    }
}


Use TakeWhile with index

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
   public static void Main(){
       int[] numbers = { 1, 3, 5, 4};
       var query = numbers.TakeWhile(( n, index) => n >= index);
       var query2 = numbers.SkipWhile(( n, index) => n >= index);
    }
}