Csharp/C Sharp by API/System.Linq/Queryable

Материал из .Net Framework эксперт
Версия от 12:11, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Queryable.All

  
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");
   }
}


Queryable.Concat

  
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, 2, 3, 4, 5, 6, 7, 8, 9 };
       int[] moreNumbers = { 10, 11, 12, 13 };
       var query = numbers.Concat(moreNumbers);
   }
}


Queryable.Contains

  
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 contains = presidents.Contains("H");
        Console.WriteLine(contains);
    }
}


Queryable.Count()

  
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"};
        int count = presidents.Count();
        Console.WriteLine(count);
    }
}


Queryable.Distinct()

  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        int[] factorsOf300 = { 2, 2, 3, 5, 5 };
        int uniqueFactors = factorsOf300.Distinct().Count();
        Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);
    }
}


Queryable.Except

  
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, 2, 3, 4};
            int[] numbers2 = {1, 1, 3, 3};
            Console.Write(numbers.Except(numbers2));
   }
}


Queryable.First

  
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, 2, 3, 4, 5, 6, 7, 8, 9 };
       var query = numbers.First();
       Console.WriteLine("The first element in the sequence");
       Console.Write(query);
       query = numbers.Last();
       Console.WriteLine("The last element in the sequence");
       Console.Write(query);
       Console.WriteLine("The first even element in the sequence");
       query = numbers.First(n => n % 2 == 0);
       Console.Write(query);
       Console.WriteLine("The last even element in the sequence");
       query = numbers.Last(n => n % 2 == 0);
       Console.Write(query);
   }
}


Queryable.First(filter)

  

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"};
        string name = presidents.First(p => p.StartsWith("H"));
        Console.WriteLine(name);
    }
}


Queryable.FirstOrDefault

  
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, 7, 9 };
            var query = numbers.FirstOrDefault(n => n % 2 == 0);
            Console.WriteLine("The first even element in the sequence");
            Console.Write(query);
            Console.WriteLine("The last odd element in the sequence");
            query = numbers.LastOrDefault(n => n % 2 == 1);
            Console.Write(query);
   }
}


Queryable.Intersect

  
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, 1, 2, 3, 3};
            int[] numbers2 = {1, 3, 3, 4};
            Console.Write(numbers.Intersect(numbers2));
   }
}


Queryable.Last()

  
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"};
        string name = presidents.Last();
        Console.WriteLine(name);
    }
}


Queryable.LastOrDefault(filter)

  
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, 7, 9 };
            var query = numbers.FirstOrDefault(n => n % 2 == 0);
            Console.WriteLine("The first even element in the sequence");
            Console.Write(query);
            Console.WriteLine("The last odd element in the sequence");
            query = numbers.LastOrDefault(n => n % 2 == 1);
            Console.Write(query);
   }
}


Queryable.LongCount()

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        long count = Enumerable.Range(0, int.MaxValue).Concat(Enumerable.Range(0, int.MaxValue)).LongCount();
        Console.WriteLine(count);
    }
}


Queryable.LongCount(filter)

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        long count = Enumerable.Range(0, int.MaxValue).
        Concat(Enumerable.Range(0, int.MaxValue)).LongCount(n => n > 1 && n < 4);
        Console.WriteLine(count);
    }
}


Queryable.Max

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        int[] myInts = new int[] { 974, 2, 7, 1374, 27, 54 };
        int maxInt = myInts.Max();
        Console.WriteLine(maxInt);
    }
}


Queryable.Max(filter)

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Employee {
    public int birthYear;
    public string firstName;
    public string lastName;
    public static Employee[] GetEmployees() {
        Employee[] actors = new Employee[] {
        new Employee { birthYear = 1964, firstName = "K", lastName = "R" },
        new Employee { birthYear = 1968, firstName = "O", lastName = "W" },
        new Employee { birthYear = 1960, firstName = "J", lastName = "S" },
        new Employee { birthYear = 1964, firstName = "S", lastName = "B" },
      };
        return (actors);
    }
}
public class MainClass {
    public static void Main() {
        int youngestEmployeeAge = Employee.GetEmployees().Max(a => a.birthYear);
        Console.WriteLine(youngestEmployeeAge);
    }
}


Queryable.Min()

  
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    public static void Main() {
        int[] numbers = { 10, 9, 8, 7, 6 };
        int count = numbers.Count();          
        int min = numbers.Min();              
    }
}


Queryable.Min(filter)

  

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Employee {
    public int birthYear;
    public string firstName;
    public string lastName;
    public static Employee[] GetEmployees() {
        Employee[] actors = new Employee[] {
        new Employee { birthYear = 1964, firstName = "Keanu", lastName = "Reeves" },
        new Employee { birthYear = 1968, firstName = "Owen", lastName = "Wilson" },
        new Employee { birthYear = 1960, firstName = "James", lastName = "Spader" },
        new Employee { birthYear = 1964, firstName = "Sandra", lastName = "Bullock" },
      };
        return (actors);
    }
}
public class MainClass {
    public static void Main() {
        int oldestEmployeeAge = Employee.GetEmployees().Min(a => a.birthYear);
        Console.WriteLine(oldestEmployeeAge);
    }
}


Queryable.OfType

  
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
   public static void Main(){
            object[] sequence = {1, "Hello", 2.0};
            Console.Write(sequence.OfType<double>());
   }
}


Queryable.OrderBy

  
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    public static void Main() {
        string[] musos = { "D C", "R B", "W A" };
        IEnumerable<string> query = musos.OrderBy(m => m.Split().Last());
    }
}


Queryable.OrderByDescending

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"ant", "arding", "arrison", "eyes", "over", "Jackson"};
        IEnumerable<string> items = presidents.OrderByDescending(s => s);
        foreach (string item in items)
            Console.WriteLine(item);
    }
}


Queryable.Reverse

  
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    public static void Main() {
        int[] numbers = { 10, 9, 8, 7, 6 };
        IEnumerable<int> reversed = numbers.Reverse();    // { 6, 7, 8, 9, 10 }
    }
}


Queryable.SelectMany

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"ant", "arding", "rison", "eyes", "over", "ackson"};
        IEnumerable<string> items = new[] {
                                   presidents.Take(5),
                                   presidents.Skip(5)
                                  }.SelectMany(s => s);
        foreach (string item in items)
            Console.WriteLine(item);
    }
}


Queryable.SequenceEqual

  
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 eq = presidents.SequenceEqual(presidents);
        Console.WriteLine(eq);
    }
}


Queryable.Single

  
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, 2, 3, 4, 5, 6, 7, 8, 9};
            var query = numbers.Single(n => n > 8);
            Console.Write(query);
   }
}


Queryable.SingleOrDefault

  
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, 2, 3, 4, 5, 6, 7, 8, 9};
       var query = numbers.SingleOrDefault(n => n > 9);
       Console.Write(query);
   }
}


Queryable.Skip

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"ant", "arding", "rison", "eyes", "over", "ackson"};
        IEnumerable<string> items = new[] {
                                   presidents.Take(5),
                                   presidents.Skip(5)
                                  }.SelectMany(s => s);
        foreach (string item in items)
            Console.WriteLine(item);
    }
}


Queryable.SkipWhile

  
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);
    }
}


Queryable.SkipWhile(filter)

  
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 allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);
            
            Console.WriteLine("All elements starting from first element divisible by 3:");
            foreach (var n in allButFirst3Numbers) {
                Console.WriteLine(n);
            }
        }
}


Queryable.StartsWith

  
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"};
        int count = presidents.Count(s => s.StartsWith("H"));
        Console.WriteLine(count);
    }
}


Queryable.Sum()

  

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Reflection;
public class MainClass{
   public static void Main(){
            int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            var query = numbers.Sum();
   }
}


Queryable.Sum(projection)

  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        string[] words = { "cherry", "apple", "blueberry" };
        double totalChars = words.Sum(w => w.Length);
        Console.WriteLine("There are a total of {0} characters in these words.", totalChars);
    }
}


Queryable.Take

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"ant", "arding", "arrison", "eyes", "over", "ackson"};
        IEnumerable<string> items = presidents.Take(5).Concat(presidents.Skip(5));
        foreach (string item in items)
            Console.WriteLine(item);
    }
}


Queryable.TakeWhile

  
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);
    }
}


Queryable.TakeWhile(filter)

  
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);
            }
        }
}


Queryable.ThenBy

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"ant", "arding", "arrison", "eyes", "over", "Jackson"};
        IEnumerable<string> items = presidents.OrderBy(s => s.Length).ThenBy(s => s);
        foreach (string item in items)
            Console.WriteLine(item);
    }
}


Queryable.ThenByDescending

  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class CaseInsensitiveComparer : IComparer<string> {
    public int Compare(string x, string y) {
        return string.rupare(x, y, true);
    }
}
public class MainClass {
    public static void Main() {
        string[] words = { "a", "A", "b", "B", "C", "c" };
        var sortedWords =
            words.OrderBy(a => a.Length)
                    .ThenByDescending(a => a, new CaseInsensitiveComparer());
        foreach (var s in sortedWords) {
            Console.WriteLine(s);
        }
    }
}


Queryable.ToArray

  
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"};
        string[] names = presidents.OfType<string>().ToArray();
        foreach (string name in names)
            Console.WriteLine(name);
    }
}


Queryable.ToDictionary

  
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
   public static void Main(){
            var q = from m in typeof(int).GetMethods()
                    group m by m.Name into gb
                    select gb;
            Dictionary<string, int> d = q.ToDictionary(k => k.Key, k => k.Count());
   }
}


Queryable.ToDictionary(filter)

  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        var scoreRecords = new[] { new {Name = "A", Score = 50},
                                new {Name = "B" , Score = 40},
                                new {Name = "C", Score = 45}
                              };
        var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
        Console.WriteLine("Bob"s score: {0}", scoreRecordsDict["Bob"]);
    }
}


Queryable.ToList()

  
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"};
        List<string> names = presidents.ToList();
        foreach (string name in names)
            Console.WriteLine(name);
    }
}


Queryable.Union

  
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, 1, 3, 3};
            int[] numbers2 = {1, 2, 3, 4};
            Console.Write(numbers.Union(numbers2));
   }
}