C# Linq

using ClassLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace LinqExam
{
    class Program
    {
        static void Main(string[] args)
        {
            //LinqQuery();
            //ExtentionMethods();
            //DeferredQuery();
            //WhereFunc();
            //WhereIndexFunc();
            //WhereTypeFunc();
            //CompoundFromFunc();
            //OrderbyLinqFunc();
            //OrderbyExtentionFunc();
            //GroupLinqFunc();
            //GroupExtentionFunc();
            //JoinLinqFunc();
            //IntersectFunc();
            //ZipFunc();
            //PageFunc();
            //CountFunc();
            SumFunc();
            
            Console.Read();
        }


        static void LinqQuery()
        {
            var query = from r in Formula.GetChampions()
                        where r.Country == "Brazil"
                        orderby r.Wins descending
                        select r;
            foreach (var r in query)
            {
                Console.WriteLine("{0:A}", r);
            }
        }


        static void ExtentionMethods()
        {
            var champions = Formula.GetChampions();
            IEnumerable<Racer> brazilChampions =
                champions.Where(r => r.Country == "Brazil").
                OrderByDescending(r=>r.Wins).
                Select(r => r);


            foreach (var r in brazilChampions)
            {
                Console.WriteLine("{0:A}", r);
            }
        }


        static void DeferredQuery()
        {
            var names = new List<string> { "Nino", "Alberto", "Juan", "Mike", "Phil" };


            var namesWithJ = from n in names
                             where n.StartsWith("J")
                             orderby n
                             select n;


            Console.WriteLine("First iteration");
            foreach (string name in namesWithJ)
            {
                Console.WriteLine(name);
            }
            Console.WriteLine();


            names.Add("John");
            names.Add("Jim");
            names.Add("Jack");
            names.Add("Denny");


            Console.WriteLine("Second iteration");
            foreach (string name in namesWithJ)
            {
                Console.WriteLine(name);
            }


        }


        //筛选
        static void WhereFunc()
        {
            var champions = Formula.GetChampions();
            var query = champions.Where(r=>r.Wins>15&&(r.Country=="Brazil" ||r.Country=="Austria"));
            foreach (var r in query)
            {
                Console.WriteLine("{0:A}", r);
            }
        }
        //索引筛选
        static void WhereIndexFunc()
        {
            var query = Formula.GetChampions().Where((r, index) => r.LastName.StartsWith("A") && index % 2 != 0);
            foreach (var r in query)
            {
                Console.WriteLine("{0:A}", r);
            }
        }


        //类型筛选
        static void WhereTypeFunc()
        {
            object[] data = { "abc", 123, "ggg" };
            var query = data.OfType<string>();
            foreach (var r in query)
            {
                Console.WriteLine(r);
            }
        }


        //复合的from语句
        static void CompoundFromFunc()
        {
            var query = from r in Formula.GetChampions()
                        from c in r.Cars
                        where c == "Ferrari"
                        select r.FirstName + " " + r.LastName;
            foreach (var s in query)
            {
                Console.WriteLine(s);
            }
        }


        //排序 linq写法
        static void OrderbyLinqFunc()
        {
            var query = (from r in Formula.GetChampions()
                         orderby r.Country, r.LastName, r.FirstName
                         select r).Take(10);
            foreach (var r in query)
            {
                Console.WriteLine("{0:A}", r);
            }
        }


        //排序 扩展写法
        static void OrderbyExtentionFunc()
        {
            var query = Formula.GetChampions()
                .OrderBy(r => r.Country)
                .ThenBy(r => r.LastName)
                .ThenBy(r => r.FirstName)
                .Select(r => r).Take(10);
            foreach (var r in query)
            {
                Console.WriteLine("{0:A}", r);
            }
        }


        //分组 linq写法
        static void GroupLinqFunc()
        {
            var query = from r in Formula.GetChampions()
                        group r by r.Country into g
                        orderby g.Count() descending, g.Key
                        where g.Count() >= 2
                        select
                        new
                        {
                            Country = g.Key,
                            Count = g.Count()
                        };
            foreach (var item in query)
            {
                Console.WriteLine("{0:-10} {1}",item.Country,item.Count);
            }
        }


        //分组 扩展写法
        static void GroupExtentionFunc()
        {
            var query = Formula.GetChampions()
                .GroupBy(r => r.Country)
                .OrderByDescending(g => g.Count())
                .ThenBy(g => g.Key)
                .Where(g => g.Count() >= 2)
                .Select(g => new { Country = g.Key, Count = g.Count() });
            foreach (var item in query)
            {
                Console.WriteLine("{0:-10} {1}", item.Country, item.Count);
            }


        }


        //连接 linq写法
        static void JoinLinqFunc()
        {
            var racers = from r in Formula.GetChampions()
                         from y in r.Years
                         where y > 2003
                         select
                         new
                         {
                             Year = y,
                             Name = r.FirstName + " " + r.LastName
                         };
            var teams = from t in Formula.GetContructorChampions()
                        from y in t.Years
                        where y > 2003
                        select
                        new
                        {
                            Year = y,
                            Name = t.Name
                        };
            var racersAndTeams = from r in racers
                                 join t in teams on r.Year equals t.Year
                                 select
                                 new
                                 {
                                     Year = r.Year,
                                     Racer = r.Name,
                                     Team = t.Name
                                 };
            foreach (var item in racersAndTeams)
            {
                Console.WriteLine(item);
            }


        }


        //集合Intersect Union Distinct Except
        static Func<string, IEnumerable<Racer>> racersByCar =
            car => from r in Formula.GetChampions()
                   from c in r.Cars
                   where c == car
                   orderby r.LastName
                   select r;
        static void IntersectFunc()
        {
            var query = racersByCar("Ferrari").Intersect(racersByCar("McLaren"));
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }


        //合并
        static void ZipFunc()
        {
            var racerNames = from r in Formula.GetChampions()
                             where r.Country == "Italy"
                             orderby r.Wins descending
                             select
                             new
                             {
                                 Name = r.FirstName + " " + r.LastName
                             };
            var racerNameAndStarts = from r in Formula.GetChampions()
                                     where r.Country == "Italy"
                                     orderby r.Wins descending
                                     select
                                     new
                                     {
                                         Name = r.LastName,
                                         Starts = r.Starts
                                     };


            var racers = racerNames.Zip(racerNameAndStarts,
                (first, second) => first.Name + ",Starts:" + second.Starts);
            foreach (var item in racers)
            {
                Console.WriteLine(item);
            }
        }


        //分区
        static void PageFunc()
        {
            int pageSize = 5;
            int pageCount = (int)Math.Ceiling(Formula.GetChampions().Count / (double)pageSize);
            for (int i = 0; i < pageCount; i++)
            {
                Console.WriteLine("Page " + i.ToString());
                var racers = (from r in Formula.GetChampions()
                              orderby r.LastName
                              select r.FirstName + " " + r.LastName).Skip(i * pageSize).Take(pageSize);
                foreach (var item in racers)
                {
                    Console.WriteLine(item);
                }
            }
        }


        //聚合 Count Sum Min Max Average Aggregate
        static void CountFunc()
        {
            var racers = from r in Formula.GetChampions()
                         where r.Years.Count() > 2
                         orderby r.Years.Count() descending
                         select
                         new
                         {
                             Name = r.FirstName + " " + r.LastName,
                             TimesChampion = r.Years.Count()
                         };
            foreach (var item in racers)
            {
                Console.WriteLine(item);
            }
        }


        static void SumFunc()
        {
            var Countries =
                (
                    from c in
                     (
                         from r in Formula.GetChampions()
                          group r by r.Country into g
                          select
                          new
                          {
                              Country = g.Key,
                              wins = (from r1 in g select r1.Wins).Sum()
                          }
                      )
                    orderby c.wins descending, c.Country
                    select c
                 ).Take(5);
            foreach (var item in Countries)
            {
                Console.WriteLine(item);
            }
        }
    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ClassLibrary
{
    [Serializable]
    public class Racer:IComparable<Racer>,IFormattable
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Country { get; set; }
        public int Wins { get; set; }
        public int Starts { get; set; }
        public string[] Cars { get; private set; }
        public int[] Years { get; private set; }


        public Racer(string firstName = null, string lastName = null, string country = null, int starts = 0, int wins = 0, IEnumerable<int> years = null, IEnumerable<string> cars = null)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Country = country;
            this.Starts = starts;
            this.Wins = wins;




            var yearsList = new List<int>();
            foreach (var year in years)
            {
                yearsList.Add(year);
            }
            this.Years = yearsList.ToArray();
            var carList = new List<string>();
            foreach (var car in cars)
            {
                carList.Add(car);
            }
            this.Cars = carList.ToArray();




        }


        public int CompareTo(Racer other)
        {
            if (other == null) throw new ArgumentNullException("other");


            return this.LastName.CompareTo(other.LastName);
        }


        public string ToString(string format, IFormatProvider formatProvider)
        {
            switch (format)
            {
                case null:
                case "N":
                    return ToString();
                case "F":
                    return FirstName;
                case "L":
                    return LastName;
                case "C":
                    return Country;
                case "S":
                    return Starts.ToString();
                case "W":
                    return Wins.ToString();
                case "A":
                    return String.Format("{0} {1}, {2}; starts: {3}, wins: {4}",
                          FirstName, LastName, Country, Starts, Wins);
                default:
                    throw new FormatException(String.Format("Format {0} not supported", format));
            }
        }


        public override string ToString()
        {
            return String.Format("{0} {1}", FirstName, LastName);
        }
        public string ToString(string format)
        {
            return ToString(format, null);
        }
    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ClassLibrary
{
    [Serializable]
    public class Team
    {
        public Team(string name, params int[] years)
        {
            this.Name = name;
            this.Years = years;
        }
        public string Name { get; private set; }
        public int[] Years { get; private set; }
    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ClassLibrary
{
    public static class Formula
    {
         private static List<Racer> racers;


        public static IList<Racer> GetChampions()
        {
            if (racers == null)
            {
                racers = new List<Racer>(40);
                racers.Add(new Racer("Nino", "Farina", "Italy", 33, 5, new int[] { 1950 }, new string[] { "Alfa Romeo" }));
                racers.Add(new Racer("Alberto", "Ascari", "Italy", 32, 10, new int[] { 1952, 1953 }, new string[] { "Ferrari" }));
                racers.Add(new Racer("Juan Manuel", "Fangio", "Argentina", 51, 24, new int[] { 1951, 1954, 1955, 1956, 1957 }, new string[] { "Alfa Romeo", "Maserati", "Mercedes", "Ferrari" }));
                racers.Add(new Racer("Mike", "Hawthorn", "UK", 45, 3, new int[] { 1958 }, new string[] { "Ferrari" }));
                racers.Add(new Racer("Phil", "Hill", "USA", 48, 3, new int[] { 1961 }, new string[] { "Ferrari" }));
                racers.Add(new Racer("John", "Surtees", "UK", 111, 6, new int[] { 1964 }, new string[] { "Ferrari" }));
                racers.Add(new Racer("Jim", "Clark", "UK", 72, 25, new int[] { 1963, 1965 }, new string[] { "Lotus" }));
                racers.Add(new Racer("Jack", "Brabham", "Australia", 125, 14, new int[] { 1959, 1960, 1966 }, new string[] { "Cooper", "Brabham" }));
                racers.Add(new Racer("Denny", "Hulme", "New Zealand", 112, 8, new int[] { 1967 }, new string[] { "Brabham" }));
                racers.Add(new Racer("Graham", "Hill", "UK", 176, 14, new int[] { 1962, 1968 }, new string[] { "BRM", "Lotus" }));
                racers.Add(new Racer("Jochen", "Rindt", "Austria", 60, 6, new int[] { 1970 }, new string[] { "Lotus" }));
                racers.Add(new Racer("Jackie", "Stewart", "UK", 99, 27, new int[] { 1969, 1971, 1973 }, new string[] { "Matra", "Tyrrell" }));
                racers.Add(new Racer("Emerson", "Fittipaldi", "Brazil", 143, 14, new int[] { 1972, 1974 }, new string[] { "Lotus", "McLaren" }));
                racers.Add(new Racer("James", "Hunt", "UK", 91, 10, new int[] { 1976 }, new string[] { "McLaren" }));
                racers.Add(new Racer("Mario", "Andretti", "USA", 128, 12, new int[] { 1978 }, new string[] { "Lotus" }));
                racers.Add(new Racer("Jody", "Scheckter", "South Africa", 112, 10, new int[] { 1979 }, new string[] { "Ferrari" }));
                racers.Add(new Racer("Alan", "Jones", "Australia", 115, 12, new int[] { 1980 }, new string[] { "Williams" }));
                racers.Add(new Racer("Keke", "Rosberg", "Finland", 114, 5, new int[] { 1982 }, new string[] { "Williams" }));
                racers.Add(new Racer("Niki", "Lauda", "Austria", 173, 25, new int[] { 1975, 1977, 1984 }, new string[] { "Ferrari", "McLaren" }));
                racers.Add(new Racer("Nelson", "Piquet", "Brazil", 204, 23, new int[] { 1981, 1983, 1987 }, new string[] { "Brabham", "Williams" }));
                racers.Add(new Racer("Ayrton", "Senna", "Brazil", 161, 41, new int[] { 1988, 1990, 1991 }, new string[] { "McLaren" }));
                racers.Add(new Racer("Nigel", "Mansell", "UK", 187, 31, new int[] { 1992 }, new string[] { "Williams" }));
                racers.Add(new Racer("Alain", "Prost", "France", 197, 51, new int[] { 1985, 1986, 1989, 1993 }, new string[] { "McLaren", "Williams" }));
                racers.Add(new Racer("Damon", "Hill", "UK", 114, 22, new int[] { 1996 }, new string[] { "Williams" }));
                racers.Add(new Racer("Jacques", "Villeneuve", "Canada", 165, 11, new int[] { 1997 }, new string[] { "Williams" }));
                racers.Add(new Racer("Mika", "Hakkinen", "Finland", 160, 20, new int[] { 1998, 1999 }, new string[] { "McLaren" }));
                racers.Add(new Racer("Michael", "Schumacher", "Germany", 250, 91, new int[] { 1994, 1995, 2000, 2001, 2002, 2003, 2004 }, new string[] { "Benetton", "Ferrari" }));
                racers.Add(new Racer("Fernando", "Alonso", "Spain", 132, 21, new int[] { 2005, 2006 }, new string[] { "Renault" }));
                racers.Add(new Racer("Kimi", "Räikkönen", "Finland", 148, 17, new int[] { 2007 }, new string[] { "Ferrari" }));
                racers.Add(new Racer("Lewis", "Hamilton", "UK", 44, 9, new int[] { 2008 }, new string[] { "McLaren" }));
            }


            return racers;
        }




        private static List<Team> teams;
        public static IList<Team> GetContructorChampions()
        {


            if (teams == null)
            {
                teams = new List<Team>()
                {
                    new Team("Vanwall", 1958),
                    new Team("Cooper", 1959, 1960),
                    new Team("Ferrari", 1961, 1964, 1975, 1976, 1977, 1979, 1982, 1983, 1999, 2000, 2001, 2002, 2003, 2004, 2007, 2008),
                    new Team("BRM", 1962),
                    new Team("Lotus", 1963, 1965, 1968, 1970, 1972, 1973, 1978),
                    new Team("Brabham", 1966, 1967),
                    new Team("Matra", 1969),
                    new Team("Tyrrell", 1971),
                    new Team("McLaren", 1974, 1984, 1985, 1988, 1989, 1990, 1991, 1998),
                    new Team("Williams", 1980, 1981, 1986, 1987, 1992, 1993, 1994, 1996, 1997),
                    new Team("Benetton", 1995),
                    new Team("Renault", 2005, 2006 )
                };
            }
            return teams;
        }
    }
}

原文地址:https://www.cnblogs.com/dxmfans/p/9434795.html