Csharp/CSharp Tutorial/LINQ/OrderBy

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

An array of string values sorted first by length, then sorted alphabetically, using a case-insentive comparison.

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)
                    .ThenBy(a => a, new CaseInsensitiveComparer());
        Console.Write(sortedWords);
    }
}

First OrderBy Prototype

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.OrderBy(s => s.Length);
        foreach (string item in items)
            Console.WriteLine(item);
    }
}

Icecreams with Least Price

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> icecreamsList3 = new List<Icecream>{
                    new Icecream("A", 10.5),
                    new Icecream("B", 9.80 ),
                    new Icecream("C", 7.5)
                    
            };
            var icecreamswithLeastPrice =from Ice in icecreamsList3 where Ice.price <= 10 select new { Ice.name, Ice.price };
            foreach (var ice in icecreamswithLeastPrice)
            {
                Console.WriteLine(ice.name + " " + ice.price);
            }
            var count = icecreamsList3.Count<Icecream>(Ice => Ice.price <= 10);
            Console.WriteLine(count);
        }
      
    }

    public class Icecream
    {
        public string name;
        public double price;
        public Icecream(string name, double price)
        {
            this.name = name;
            this.price = price;
        }
    }

Multi Level Ordering

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="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 }
           };
            var queryResults =
                from c in customers
                orderby c.Region, c.Country descending, c.City
                select new { c.ID, c.Region, c.Country, c.City }
               ;
            foreach (var item in queryResults)
            {
                Console.WriteLine(item);
            }
        }
    }

Not in Top Five Customers by Sales

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="N", City="Los Angeles", Country="USA", Region="North America", Sales=5000 },
              new Customer { ID="O", City="Cairo", Country="Egypt", Region="Africa", Sales=6000 },
              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 }
           };
            var queryResults =
                from c in customers
                orderby c.Sales descending
                select new { c.ID, c.City, c.Country, c.Sales }
               ;
            Console.WriteLine("Customers Not In Top Five");
            foreach (var item in queryResults.Skip(5))
            {
                Console.WriteLine(item);
            }

        }
    }

Order by descending

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
    class Employee
    {
        public string Name { get; set; }
        public decimal Salary { get; set; }
    }
    class Department
    {
        public string Name { get; set; }
        List<Employee> employees = new List<Employee>();
        public IList<Employee> Employees
        {
            get { return employees; }
        }
    }
    class Company
    {
        public string Name { get; set; }
        List<Department> departments = new List<Department>();
        public IList<Department> Departments
        {
            get { return departments; }
        }
    }
    class SalaryReport
    {
        static void Main()
        {
            var company = new Company
            {
                Name = "A",
                Departments =
                {
                    new Department 
                    { 
                        Name = "Development", 
                        Employees = 
                        {
                            new Employee { Name = "T", Salary = 75000m },
                            new Employee { Name = "D", Salary = 45000m },
                            new Employee { Name = "M", Salary = 150000m }
                        }
                    },
                    new Department 
                    { 
                        Name = "Marketing", 
                        Employees = 
                        {
                            new Employee { Name = "Z", Salary = 200000m },
                            new Employee { Name = "X", Salary = 120000m }
                        }
                    }
                }
            };
            var query = company.Departments
                               .Select(dept => new { dept.Name, Cost = dept.Employees.Sum(person => person.Salary) })
                               .OrderByDescending(deptWithCost => deptWithCost.Cost);
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }

OrderBy: prints an alphabetically sorted version of a string array

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        string[] words = { "C", "a", "b" };
        var sortedWords =
            from w in words
            orderby w
            select w;
        Console.WriteLine("The sorted list of words:");
        foreach (var w in sortedWords) {
            Console.WriteLine(w);
        }
    }
}

OrderBy with customized Comparer

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, new CaseInsensitiveComparer());

    }
}

OrderBy with passing a lambda function

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, new CaseInsensitiveComparer());

    }
}

Ordered by PetName

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 orderby c.PetName select c;
            
            foreach (Car c in subset)
            {
                Console.WriteLine(c.ToString());
            }
        
        }
    }

Order 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.OrderBy(n => n).Where(n => n.StartsWith("S"));
            foreach (var item in queryResults)
            {
                Console.WriteLine(item);
            }
        }
    }

Order Query Results

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

products sorted alphabetically by the product name

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        List<Product> products = GetProductList();
        var sortedProducts =
            from p in products
            orderby p.ProductName
            select p;
        Console.WriteLine(sortedProducts);
    }
    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;
    }
}

products sorted by the number of units of each product that are in stock

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        List<Product> products = GetProductList();
        var sortedProducts =
            from p in products
            orderby p.UnitsInStock descending
            select p;
        Console.Write(sortedProducts);
    }
    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;
    }
}

sorted alphabetically in descending order, using a case insensitive comparision.

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.OrderByDescending(a => a, new CaseInsensitiveComparer());
    }
}

Sorted join query

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 Address
    {
        public string Name   { get; set; }
        public string Street { get; set; }
        public string City   { get; set; }
        public override string ToString()
        {
            return string.Format("{0}, {1}", Street, City);
        }
    }
    public class CustomerAddress
    {
        public Customer Customer { get; set; }
        public Address Address { get; set; }
    }
    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" }
                };
            List<Address> addresses = new List<Address>
                {
                    new Address { Name   = "J",
                                  Street = "165 Main", 
                                    City = "City 1" },
                    new Address { Name   = "K H",
                                  Street = "3207 Way", 
                                    City = "Cith 2" },
                    new Address { Name   = "J G",
                                  Street = "800 Blvd.", 
                                    City = "City 3" },
                    new Address { Name   = "Mary",
                                  Street = "7 Ave", 
                                    City = "City 4" },
                    new Address { Name   = "Kate",
                                  Street = "2251 Avenue", 
                                    City = "City 5" }
                };
            var result = from customer in customers
                join address in addresses on
                     string.Format("{0} {1}", customer.FirstName, customer.LastName) 
                     equals address.Name
                orderby customer.LastName, address.Street descending  
                select new { Customer = customer, Address = address };
            foreach (var ca in result)
            {
                Console.WriteLine(string.Format("{0}\nAddress: {1}",
                    ca.Customer, ca.Address));
            }
        }
    }

Sorting strings in a file

using System;
using System.IO;
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<string> strs = new List<string>();
            using( StreamReader sReader = new StreamReader("data.txt"))
            {
              string str;
              str = sReader.ReadLine();
              while (str != null)
              {
                strs.Add(str);
              }
            }
            IEnumerable<string> i = from name in strs orderby name descending select name;
            foreach (string nam in i)
            {
              Console.WriteLine(nam);
            }
        }
    }

Sort object by its property

using System;
using System.Collections.Generic;
using System.ruponentModel;
        class Film
        {
            public string Name { get; set; }
            public int Year { get; set; }
            public override string ToString()
            {
                return string.Format("Name={0}, Year={1}", Name, Year);
            }
        }
    class MainClass
    {
        static void Main()
        {
            var films = new List<Film>
            {
                new Film {Name="J", Year=1975},
                new Film {Name="H", Year=2000},
                new Film {Name="T", Year=1995}
            };
            Action<Film> print = film => Console.WriteLine(film);
            Console.WriteLine("All films");
            films.ForEach(print);                                
            Console.WriteLine();
            Console.WriteLine("Oldies");
            films.FindAll(film => film.Year < 1980).ForEach(print);
            Console.WriteLine();
            Console.WriteLine("Sorted");
            films.Sort((f1, f2) => f1.Name.rupareTo(f2.Name));  
            films.ForEach(print);                                
        }        
    }

string array sorted by the length each element

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        string[] words = { "abc", "bcd", "def" };
        var sortedWords =
            from w in words
            orderby w.Length
            select w;
        Console.WriteLine("The sorted list of words (by length):");
        foreach (var w in sortedWords) {
            Console.WriteLine(w);
        }
    }
}

Top Five Customers by Sales

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="N", City="Los Angeles", Country="USA", Region="North America", Sales=5000 },
              new Customer { ID="O", City="Cairo", Country="Egypt", Region="Africa", Sales=6000 },
              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 }
           };
            var queryResults =
                from c in customers
                orderby c.Sales descending
                select new { c.ID, c.City, c.Country, c.Sales }
               ;
            Console.WriteLine("Top Five Customers by Sales");
            foreach (var item in queryResults.Take(5))
            {
                Console.WriteLine(item);
            }

        }
    }

Using a compound orderby to sort a list of digits first by length of their name, and then alphabetically.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        string[] digits = { "zero", "one", "two", "three"};
        var sortedDigits =
            from d in digits
            orderby d.Length, d
            select d;
        Console.WriteLine("Sorted digits:");
        foreach (var d in sortedDigits) {
            Console.WriteLine(d);
        }
    }
}

Using a compound orderby to sort a list of products, first by category, and then by unit price, from highest to lowest.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        List<Product> products = GetProductList();
        var sortedProducts =
            from p in products
            orderby p.Category, p.UnitPrice descending select p;
        foreach (var s in sortedProducts) {
            Console.Write(s);
        }
    }
    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 orderby clause to order result

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

Where with OrderBy

using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    public static void Main() {
        string[] names = { "J", "P", "G", "Pa" };
        IEnumerable<string> query = names.Where(n => n.Contains("a"))
                                         .OrderBy(n => n.Length)
                                         .Select(n => n.ToUpper());
    }
}