Csharp/CSharp Tutorial/LINQ/where

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

A Query Using the Standard Dot Notation Syntax

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] names = { "A1", "B123", "C123123", "E", "W" };
        IEnumerable<string> sequence = names
         .Where(n => n.Length < 6)
         .Select(n => n);
        foreach (string name in sequence) {
            Console.WriteLine("{0}", name);
        }
    }
}

Assign the loop variable to another variable declared inside the statement block

using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    public static void Main() {
        IEnumerable<char> vowels = "aeiou";
        IEnumerator<char> rator = vowels.GetEnumerator();
        IEnumerable<char> query = "Not what you might expect";

        foreach (char vowel in "aeiou") {
            char temp = vowel;
            query = query.Where(c => c != temp);
        }
    }
}

Display Products With Unknown Price

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Linq;
    class ProductWithNullablePrice
    {
        public string Name { get; private set; }
        public decimal? Price { get; private set; }
        public ProductWithNullablePrice(string name, decimal price)
        {
            Name = name;
            Price = price;
        }
        ProductWithNullablePrice()
        {
        }
        public static List<ProductWithNullablePrice> GetSampleProducts()
        {
            return new List<ProductWithNullablePrice>
            {
                new ProductWithNullablePrice { Name="C", Price= 9.99m },
                new ProductWithNullablePrice { Name="A", Price= 4.99m },
                new ProductWithNullablePrice { Name="F", Price= 3.99m },
                new ProductWithNullablePrice { Name="S", Price=null}
            };
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", Name, Price);
        }
    }
    class MainClass
    {
        static void Main()
        {
            List<ProductWithNullablePrice> products = ProductWithNullablePrice.GetSampleProducts();
            foreach (ProductWithNullablePrice product in products.Where(p => p.Price == null))
            {
                Console.WriteLine(product.Name);
            }
        }
    }

Filter by Make and Speed

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using System.Linq;
    class Car
    {
        public string PetName;
        public string Color;
        public int Speed;
        public string Make;
        
        public override string ToString()
        {
            return string.Format("Make={0}, Color={1}, Speed={2}, PetName={3}",Make, Color, Speed, PetName);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Car[] myCars = new []{
                new Car{ PetName = "A", Color = "Silver", Speed = 100, Make = "BMW"},
                new Car{ PetName = "B", Color = "Black", Speed = 55, Make = "VW"},
                new Car{ PetName = "C", Color = "White", Speed = 43, Make = "Ford"}
            };
        
            var a = from c in myCars
                               where c.Make == "BMW" && c.Speed >= 100 
                               select c;
            foreach (Car c in a)
            {
                Console.WriteLine(c.ToString());
            }
        
        }
    }

Filtered: prints the name of each element of an integer array that is less than 5

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};
        string[] digits = { "zero", "one", "two", "three"};
        var lowNums =
            from n in numbers
            where n < 5
            select digits[n];
        Console.WriteLine("Numbers < 5:");
        foreach (var num in lowNums) {
            Console.WriteLine(num);
        }
    }
}

Filter string by its length

using System;
using System.Collections.Generic;
using System.Linq;
class LinqDemo {
    static void Main() {
        string[] names = { "Tom", "Dick", "Harry" };

        IEnumerable<string> filteredNames = names.Where(n => n.Length >= 4);
        foreach (string name in filteredNames) Console.Write(name + "|");
    }
}

Get upper case chars

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Xml.Linq;
    class Program
    {
        static void Main(string[] args)
        {
            String aString = "this is a test";
            
            IEnumerable<char> query = from ch in aString where Char.IsUpper(ch) select ch;

        }
    }

Ice Creams with price less than 10

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Xml.Linq;
class Program
{
    static void Main(string[] args)
    {
        List<Icecream> icecreamsList = new List<Icecream> 
            {
              new Icecream {Name="A", Price=10.5 },
              new Icecream {Name="B", Price=9.80 },
              new Icecream {Name="C", Price=7.5 }
            };
        IEnumerable<Icecream> i = from ice in icecreamsList where ice.Price < 10 select ice;
        foreach (Icecream ice in i)
        {
            Console.WriteLine("{0} is {1}", ice.Name, ice.Price);
        }
    }
}
public class Icecream
{
    public string Name { get; set; }
    public double Price { get; set; }
}

LINQ Method Syntax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
    class Program{
        static void Main(string[] args)
        {
            string[] names = { "Zheng", "Smith"};
            var queryResults = names.Where(n => n.StartsWith("S"));
            foreach (var item in queryResults)
            {
                Console.WriteLine(item);
            }
        }
    }

LINQ query to get strings starting with s

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = { "Alonso", "Zheng", "Smith" };
            var queryResults =
                from n in names
                where n.StartsWith("S")
                select n;
            foreach (var item in queryResults)
            {
                Console.WriteLine(item);
            }
        }
    }

prints strings where each element has the second letter "i".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        string[] digits = { "ziro", "one", "two", "three"};
        var reversedIDigits = (
            from d in digits
            where d[1] == "i"
            select d)
            .Reverse();
        foreach (var d in reversedIDigits) {
            Console.WriteLine(d);
        }
    }
}

Query by string length with Linq

using System;
  using System.Linq;
  class Program
  {
      static void Main(string[] args)
      {
          string[] colors = {"Red", "Orange", "Yellow", "Green"};
          var colorQuery = from color in colors
                           where color.Length <= 5
                           orderby color
                           select color;
          foreach (string s in colorQuery)
              Console.WriteLine(s);
          Console.WriteLine("\nPress any key to continue.");
          
      }
  }

Query for filtering numbers

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
    class Program
    {
        static void Main(string[] args)
        {
            Random generator = new Random(0);
            int[] numbers = new int[1000];
            for (int i = 0; i < 1000; i++)
            {
                numbers[i] = generator.Next();
            }
            
            var queryResults = from n in numbers where n < 100 select n;      
            foreach (var item in queryResults)
            {
                Console.WriteLine(item);
            }
        }
    }

Query string value by String.StartsWith

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"Ad", "Ar", "Bu", "B", "C", "C"};
        string president = presidents.Where(p => p.StartsWith("Ad")).First();
        Console.WriteLine(president);
    }
}

Query Using the Query Expression Syntax

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] names = { "A123123", "B123", "C123123", "E123", "W" };
        IEnumerable<string> sequence = from n in names
                                       where n.Length < 6
                                       select n;
        foreach (string name in sequence) {
            Console.WriteLine("{0}", name);
        }
    }
}

Query with an Exception

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"AAAA", "aaaa", "bacDert", "B1234", "Carter"};
        IEnumerable<string> items = presidents.Where(s => Char.IsLower(s[4]));
        Console.WriteLine("After the query.");
        foreach (string item in items)
            Console.WriteLine(item);
    }
}

Search Customers by first name

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAddress { get; set; }
        public override string ToString()
        {
            return string.Format("{0} {1}\nEmail:   {2}",FirstName, LastName, EmailAddress);
        }
    }
    public class Tester
    {
        static void Main()
        {
            List<Customer> customers = new List<Customer>{
                    new Customer { FirstName = "A", 
                                    LastName = "B",
                                    EmailAddress = "o@a.ru"},
                    new Customer { FirstName = "C", 
                                    LastName = "H",
                                    EmailAddress = "k@a.ru" },
                    new Customer { FirstName = "D", 
                                    LastName = "C",
                                    EmailAddress = "d@a.ru" },
                    new Customer { FirstName = "J", 
                                    LastName = "G",
                                    EmailAddress = "j@a.ru" },
                    new Customer { FirstName = "L", 
                                    LastName = "H",
                                    EmailAddress = "l@a.ru" }
            };
            IEnumerable<Customer> result = from customer in customers where customer.FirstName == "D" select customer;
            List<Customer> cachedResult = result.ToList<Customer>();
            foreach (Customer customer in cachedResult)
                Console.WriteLine(customer.ToString());
            customers[3].FirstName = "Donna";
            foreach (Customer customer in cachedResult)
                Console.WriteLine(customer.ToString());
        }
    }

Simple method based query

using System;
using System.Linq;
  class Program
  {
    static void Main(string[] args)
    {
      string[] names = {"Jesse", "Donald", "Mary"};
      var dNames = names.Where(n => n.StartsWith("D"));
      foreach (string foundName in dNames)
      {
        Console.WriteLine("Found: " + foundName);
      }
    }
  }

To remove all vowels from a string.

using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    public static void Main() {
        IEnumerable<char> query = "Not what you might expect";
        query = query.Where(c => c != "a");
        query = query.Where(c => c != "e");
        query = query.Where(c => c != "i");
        query = query.Where(c => c != "o");
        query = query.Where(c => c != "u");
        foreach (char c in query) Console.Write(c); 
    }
}

Two where clauses

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
class Employee {
    int _id;
    int _idRole;
    string _lastName;
    string _firstName;
    public int ID {
        get { return _id; }
        set { _id = value; }
    }
    public int IDRole {
        get { return _idRole; }
        set { _idRole = value; }
    }
    public string LastName {
        get { return _lastName; }
        set { _lastName = value; }
    }
    public string FirstName {
        get { return _firstName; }
        set { _firstName = value; }
    }
}
class Salary {
    int _id;
    int _year;
    double _salary;
    public int ID {
        get { return _id; }
        set { _id = value; }
    }
    public int Year {
        get { return _year; }
        set { _year = value; }
    }
    public double SalaryPaid {
        get { return _salary; }
        set { _salary = value; }
    }
}
public class MainClass {
    public static void Main() {
        List<Employee> people = new List<Employee> {
              new Employee  { ID = 1, IDRole = 1, LastName = "A", FirstName = "B"},
              new Employee  { ID = 2, IDRole = 2, LastName = "G", FirstName = "T"}
            };
        List<Salary> salaries = new List<Salary> {
               new Salary { ID = 1, Year = 2004, SalaryPaid = 10000.00 },
               new Salary { ID = 1, Year = 2005, SalaryPaid = 15000.00 },
               new Salary { ID = 1, Year = 2005, SalaryPaid = 15000.00 }
            };
        IEnumerable<Salary> q = from p in people
                                where p.ID == 1
                                from s in salaries
                                where s.ID == p.ID
                                select s;

    }
}

Use && in where clause

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        List<Product> products = GetProductList();
        var expensiveInStockProducts =
            from p in products
            where p.UnitsInStock > 0 && p.UnitPrice > 3.00M
            select p;
        foreach (var product in expensiveInStockProducts) {
            Console.WriteLine(product.ProductName);
        }
    }
    static List<Product> GetProductList() {
        List<Product> empTree = new List<Product>();
        empTree.Add(new Product { ProductName = "A", Category = "O", UnitPrice = 12, UnitsInStock = 5, Total = 36, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "B", Category = "O", UnitPrice = 2, UnitsInStock = 4, Total = 35, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "C", Category = "O", UnitPrice = 112, UnitsInStock = 3, Total = 34, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "D", Category = "O", UnitPrice = 112, UnitsInStock = 0, Total = 33, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "E", Category = "O", UnitPrice = 1112, UnitsInStock = 2, Total = 32, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "F", Category = "O", UnitPrice = 11112, UnitsInStock = 0, Total = 31, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        return empTree;
    }
}
class Product : IComparable<Product> {
    public string ProductName { get; set; }
    public string Category { get; set; }
    public int UnitPrice { get; set; }
    public int UnitsInStock { get; set; }
    public int Total { get; set; }
    public DateTime OrderDate { get; set; }
    public int Id { get; set; }
    public override string ToString() {
        return String.Format("Id: {0}, Name: {1} , Category: {3}", this.Id, this.ProductName, this.Category);
    }
    int IComparable<Product>.rupareTo(Product other) {
        if (other == null)
            return 1;
        if (this.Id > other.Id)
            return 1;
        if (this.Id < other.Id)
            return -1;
        return 0;
    }
}

Use string method in where clause

using System;
using System.Linq;
public class MainClass {
    public static void Main() {
        string[] greetings = { "hello world", "hello LINQ", "hello" };
        var items =
         from s in greetings
         where s.EndsWith("LINQ")
         select s;
        foreach (var item in items)
            Console.WriteLine(item);
    }
}

Use where to filer object list

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        List<Product> products = GetProductList();
        var soldOutProducts =
            from p in products
            where p.UnitsInStock == 0
            select p;
        Console.WriteLine("Sold out products:");
        foreach (var product in soldOutProducts) {
            Console.WriteLine("{0} is sold out!", product.ProductName);
        }
    }
    static List<Product> GetProductList() {
        List<Product> empTree = new List<Product>();
        empTree.Add(new Product { ProductName = "A", Category = "O", UnitPrice = 12, UnitsInStock = 5, Total = 36, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "B", Category = "O", UnitPrice = 2, UnitsInStock = 4, Total = 35, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "C", Category = "O", UnitPrice = 112, UnitsInStock = 3, Total = 34, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "D", Category = "O", UnitPrice = 112, UnitsInStock = 0, Total = 33, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "E", Category = "O", UnitPrice = 1112, UnitsInStock = 2, Total = 32, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "F", Category = "O", UnitPrice = 11112, UnitsInStock = 0, Total = 31, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        return empTree;
    }
}
class Product : IComparable<Product> {
    public string ProductName { get; set; }
    public string Category { get; set; }
    public int UnitPrice { get; set; }
    public int UnitsInStock { get; set; }
    public int Total { get; set; }
    public DateTime OrderDate { get; set; }
    public int Id { get; set; }
    public override string ToString() {
        return String.Format("Id: {0}, Name: {1} , Category: {3}", this.Id, this.ProductName, this.Category);
    }
    int IComparable<Product>.rupareTo(Product other) {
        if (other == null)
            return 1;
        if (this.Id > other.Id)
            return 1;
        if (this.Id < other.Id)
            return -1;
        return 0;
    }
}

Using where clause in a while loop

using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    public static void Main() {
        IEnumerable<char> vowels = "aeiou";
        IEnumerator<char> rator = vowels.GetEnumerator();
        IEnumerable<char> query = "Not what you might expect";
        char vowel;
        while (rator.MoveNext()) {
            vowel = rator.Current;
            query = query.Where(c => c != vowel);
        }
    }
}

where clause

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Reflection;
class Person {
    int _id;
    int _idRole;
    string _lastName;
    string _firstName;
    public int ID {
        get { return _id; }
        set { _id = value; }
    }
    public int IDRole {
        get { return _idRole; }
        set { _idRole = value; }
    }
    public string LastName {
        get { return _lastName; }
        set { _lastName = value; }
    }
    public string FirstName {
        get { return _firstName; }
        set { _firstName = value; }
    }
}
class Program {
    static void Main(string[] args) {
        List<Person> people = new List<Person> {
              new Person  { ID = 1, IDRole = 1, LastName = "A", FirstName = "B"},
              new Person  { ID = 2, IDRole = 2, LastName = "G", FirstName = "T"},
              new Person  { ID = 3, IDRole = 2, LastName = "G", FirstName = "M"},
              new Person  { ID = 4, IDRole = 3, LastName = "C", FirstName = "G"}
            };
        var query = people.Where((p, index) => p.IDRole == index);
    }
}

Where clause with string method and return IEnumerable object

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {

        string[] presidents = {"AA", "A", "AAA", "B", "Ca", "C"};
        IEnumerable<string> items = presidents.Where(p => p.StartsWith("A"));
        foreach (string item in items)
            Console.WriteLine(item);
    }
}

Where Prototype

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"A", "Ar", "B", "Bu", "C", "Cleveland"};
        IEnumerable<string> sequence = presidents.Where(p => p.StartsWith("C"));
        foreach (string s in sequence)
            Console.WriteLine("{0}", s);
    }
}