Csharp/CSharp Tutorial/LINQ/foreach loop

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

Cars going faster than 55, ordered by PetName

<source lang="csharp">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 subset = from c in myCars where c.Speed > 55 orderby c.PetName descending select c;
           foreach (Car c in subset)
           {
               Console.WriteLine(c.ToString());
           }
       
       }
   }</source>

Linq over array

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

   class Program
   {
       static void Main(string[] args)
       {
           int[] numbers = { 10, 20, 30, 40, 1, 2, 3, 8 };
           var subset = from i in numbers where i < 10 select i;
           foreach (var i in subset)
               Console.Write("Item: {0} ", i);
           Console.WriteLine("resultSet is of type: {0}", subset.GetType().Name);
           Console.WriteLine("resultSet location: {0}", subset.GetType().Assembly);
       }
   }</source>

Linq Over ArrayList

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

   class Car
   {
       public string PetName;
       public string Color;
       public int Speed;
       public string Make;
   }
   class Program
   {
       static void Main(string[] args)
       {
           ArrayList myCars = new ArrayList();  
           myCars.Add(new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"});
           myCars.Add(new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"});
           myCars.Add(new Car { PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford" });
           IEnumerable<Car> myCarsEnum = myCars.OfType<Car>();
           // Create a query expression. 
           var fastCars = from c in myCarsEnum where c.Speed > 55 select c;
           foreach (var car in fastCars)
           {
               Console.WriteLine("{0} is going too fast!", car.PetName);
           }
       }
   }</source>

Linq Over Array Using Sequence

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

   class Program
   {
       static void Main(string[] args)
       {
           string[] currentVideoGames = {"test", "this is a test", "asdf", "game 1","game 2", "game 3"};
           var subset = from g in currentVideoGames where g.Length > 6 orderby g select g;
           foreach (var s in subset)
               Console.WriteLine("Item: {0}", s);
       }
   }</source>

Linq To Objects

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

   class LinqToObjects
   {
       static void Main(string[] args)
       {
           string[] names = { "test", "test 1", "Am" };
           IEnumerable<string> namesOfPeople = from name in names where name.Length <= 2 select name;
           foreach (var name in namesOfPeople)
               Console.WriteLine(name);
            
       }
   }</source>

Simple linq

<source lang="csharp">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 = "B", 
                                   LastName = "C",
                                   EmailAddress = "k@a.ru" },
                   new Customer { FirstName = "D", 
                                   LastName = "C",
                                   EmailAddress = "d@a.ru" },
                   new Customer { FirstName = "F", 
                                   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 == "Donna"
               select customer;
           foreach (Customer customer in result)
               Console.WriteLine(customer.ToString());
           customers[3].FirstName = "Donna";
           foreach (Customer customer in result)
               Console.WriteLine(customer.ToString());
       }
   }</source>

Use foreach loop to deal with the result from linq

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

   public static void Main() {
       List<Customer> customers = GetCustomerList();
       var waCustomers =
           from c in customers
           where c.Region == "R1"
           select c;
       foreach (var customer in waCustomers) {
           Console.WriteLine("Customer {0}: {1}", customer.CustomerId, customer.rupanyName);
           foreach (var order in customer.Orders) {
               Console.WriteLine(" Order {0}: {1}", order.Id, order.OrderDate);
           }
       }
   }
   static List<Customer> GetCustomerList() {
       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 });
       List<Customer> l = new List<Customer>();
       l.Add(new Customer { CompanyName = "A", Region = "R1", UnitsInStock = 1, Orders = empTree, CustomerId =0});
       l.Add(new Customer { CompanyName = "B", Region = "R2", UnitsInStock = 2, Orders = empTree, CustomerId = 1 });
       l.Add(new Customer { CompanyName = "C", Region = "R3", UnitsInStock = 3, Orders = empTree, CustomerId = 2 });
       l.Add(new Customer { CompanyName = "D", Region = "R4", UnitsInStock = 4, Orders = empTree, CustomerId = 3 });
       l.Add(new Customer { CompanyName = "E", Region = "R5", UnitsInStock = 5, Orders = empTree, CustomerId = 4 });
       return l;
   }

} class Customer : IComparable<Customer> {

   public string CompanyName { get; set; }
   public string Region { get; set; }
   public List<Product> Orders { get; set; }
   public int UnitsInStock { get; set; }
   public int CustomerId { get; set; }
   public override string ToString() {
       return String.Format("Id: {0}, Name: {1}, Region: {3}", this.CustomerId, this.rupanyName, this.Region);
   }
   int IComparable<Customer>.rupareTo(Customer other) {
       if (other == null)
           return 1;
       if (this.CustomerId > other.CustomerId)
           return 1;
       if (this.CustomerId < other.CustomerId)
           return -1;
       return 0;
   }

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

}</source>