Csharp/CSharp Tutorial/LINQ/All

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

All method

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text;

   class Customer
   {
       public string ID { get; set; }
       public string City { get; set; }
       public string Country { get; set; }
       public string Region { get; set; }
       public decimal Sales { get; set; }
   }
   class Program
   {
       static void Main(string[] args)
       {
           List<Customer> customers = new List<Customer> {
             new Customer { ID="P", City="Tehran", Country="Iran", Region="Asia", Sales=7000 },
             new Customer { ID="Q", City="London", Country="UK", Region="Europe", Sales=8000 },
             new Customer { ID="R", City="Beijing", Country="China", Region="Asia", Sales=9000 },
             new Customer { ID="T", City="Lima", Country="Peru", Region="South America", Sales=2002 }
          };
           bool allAsia = customers.All(c => c.Region == "Asia");
           Console.WriteLine (allAsia);
       }
   }</source>

All with condition

<source lang="csharp">using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; public class MainClass{

  public static void Main(){
      int[] numbers = { 2, 6, 1, 56, 102 };
      Console.Write(numbers.All(e => e % 2 == 0) ? "Yes, they are" : "No, they aren"t");
  }

}</source>

All with Predicate to Return True

<source lang="csharp">using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {

   public static void Main() {
       string[] presidents = {"G123456", "H", "a", "H", "over", "Jack"};
       bool all = presidents.All(s => s.Length > 5);
       Console.WriteLine(all);
   }

}</source>

All with string length

<source lang="csharp">using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {

   public static void Main() {
       string[] presidents = {"G", "H", "a", "H", "over", "Jack"};
       bool all = presidents.All(s => s.Length > 3);
       Console.WriteLine(all);
   }

}</source>

Using All to determine whether an array contains only odd numbers.

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MainClass {

   public static void Main() {
       int[] numbers = { 1, 11, 3, 19, 41, 65, 19 };
       bool onlyOdd = numbers.All(n => n % 2 == 1);
       Console.WriteLine("The list contains only odd numbers: {0}", onlyOdd);
   }

}</source>