Linq常见操作示例

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

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);  
     }  
  
     /*              
         First iteration 
         Juan 
         second iteration 
         Jack 
         Jim 
         John 
         Juan                               
      */  
  
 }  
  
  
 //如查询出来自巴西的所有世界冠军,并按照夺冠次数排序  
 static void LINQQuery()  
 {  
     var query = from r in Formula1.GetChampions()  
                 where r.Country == "Brazil"  
                 orderby r.Wins descending  
                 select r;  
  
     foreach (var r in query)  
     {  
         Console.WriteLine("{0:A}", r);  
     }  
 }  
  
 //Zip合并功能  
 static void ZipOperation()  
 {  
     var racerNames = from r in Formula1.GetChampions()  
                      where r.Country == "Italy"  
                      orderby r.Wins descending  
                      select new  
                      {  
                          Name = r.FirstName + " " + r.LastName  
                      };  
  
     var racerNamesAndStarts = from r in Formula1.GetChampions()  
                            where r.Country == "Italy"  
                            orderby r.Wins descending  
                            select new   
                            {  
                                LastName = r.LastName,  
                                Starts = r.Starts  
                            };  
  
  
     //var racers = racerNames.Zip(racerNamesAndStarts, (first, second) => first.Name + ", starts: " + second.Starts);  
     //foreach (var r in racers)  
     //{  
     //    Console.WriteLine(r);  
     //}  
  
 }  
  
 //根据赛手获得一级方程式冠军的次数,列出最成功的国家  
 static void Aggregate2()  
 {  
     var countries = (from c in  
                          from r in Formula1.GetChampions()  
                          group r by r.Country into c  
                          select new  
                          {  
                              Country = c.Key,  
                              Wins = (from r1 in c  
                                      select r1.Wins).Sum()  
                          }  
                      orderby c.Wins descending, c.Country  
                      select c).Take(5);  
  
     foreach (var country in countries)  
     {  
         Console.WriteLine("{0} {1}", country.Country, country.Wins);  
     }  
  
 }  
  
 //筛选赛手,只返回获得冠军次数超过3次的赛手  
 static void Aggregate()  
 {  
     var query = from r in Formula1.GetChampions()  
                 where r.Years.Count() > 3  
                 orderby r.Years.Count() descending  
                 select new  
                 {  
                     Name = r.FirstName + " " + r.LastName,  
                     TimesChampion = r.Years.Count()  
                 };  
  
     foreach (var r in query)  
     {  
         Console.WriteLine("{0} {1}", r.Name, r.TimesChampion);  
     }  
 }  
  
 //Linq分页显示  
 static void Partitioning()  
 {  
     int pageSize = 5;  
  
     int numberPages = (int)Math.Ceiling(Formula1.GetChampions().Count() /  
           (double)pageSize);  
  
     for (int page = 0; page < numberPages; page++)  
     {  
         Console.WriteLine("Page {0}", page);  
  
         var racers =  
            (from r in Formula1.GetChampions()  
             orderby r.LastName  
             select r.FirstName + " " + r.LastName).  
            Skip(page * pageSize).Take(pageSize);  
  
         foreach (var name in racers)  
         {  
             Console.WriteLine(name);  
         }  
         Console.WriteLine();  
     }  
  
 }  
  
 //有驾驶法拉利和迈凯轮的冠军,集合交集  
 static void SetOperations()  
 {  
     Func<string, IEnumerable<Racer>> racersByCar =  
         car => from r in Formula1.GetChampions()  
                from c in r.Cars  
                where c == car  
                orderby r.LastName  
                select r;  
  
     Console.WriteLine("World champion with Ferrari and McLaren");  
     foreach (var racer in racersByCar("Ferrari").Intersect(racersByCar("McLaren")))  
     {  
         Console.WriteLine(racer);  
     }  
 }  
  
 //列出每年的赛手冠军和车队冠军  
 static void Join()  
 {  
     var racers = from r in Formula1.GetChampions()  
                  from y in r.Years  
                  where y > 2003  
                  select new  
                  {  
                      Year = y,  
                      Name = r.FirstName + " " + r.LastName  
                  };  
  
     var teams = from t in  
                     Formula1.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  
           };  
  
     Console.WriteLine("Year  Champion " + "Constructor Title");  
     foreach (var item in racersAndTeams)  
     {  
         Console.WriteLine("{0}: {1,-20} {2}",  
            item.Year, item.Racer, item.Team);  
     }  
 }  
  
 //现在一级方程式冠军应按照国家分组,并列出一个国家的冠军数以及包含赛手名序列  
 static void GroupingWithNestedObjects()  
 {  
     var countries = from r in Formula1.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(),  
                         Racers = from r1 in g  
                                  orderby r1.LastName  
                                  select r1.FirstName + " " + r1.LastName  
                     };  
     foreach (var item in countries)  
     {  
         Console.WriteLine("{0, -10} {1}", item.Country, item.Count);  
         foreach (var name in item.Racers)  
         {  
             Console.Write("{0}; ", name);  
         }  
         Console.WriteLine();  
     }  
  
 }  
  
 static void Grouping()  
 {  
     var countries = from r in Formula1.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 countries)  
     {  
         Console.WriteLine("{0, -10} {1}", item.Country, item.Count);  
     }  
  
 }  
  
 //显示驾驶法拉利的所有一级方程式冠军名字  
 static void CompoundFrom()  
 {  
     var ferrariDrivers = from r in Formula1.GetChampions()  
                          from c in r.Cars  
                          where c == "Ferrari"  
                          orderby r.LastName  
                          select r.FirstName + " " + r.LastName;  
  
     foreach (var racer in ferrariDrivers)  
     {  
         Console.WriteLine(racer);  
     }  
 }  
  
 static void TypeFiltering()  
 {  
     object[] data = { "one", 2, 3, "four", "five", 6 };  
     var query = data.OfType<string>();  
     foreach (var s in query)  
     {  
         Console.WriteLine(s);  
     }  
     /* 
         one 
         four 
         five              
      */  
 }  
  
 //使用索引返回姓氏以A开头、索引为偶数的赛手  
 static void IndexFiltering()  
 {  
     var racers = Formula1.GetChampions().  
             Where((r, index) => r.LastName.StartsWith("A") && index % 2 != 0);  
     foreach (var r in racers)  
     {  
         Console.WriteLine("{0:A}", r);  
     }  
  
 }  
  
 //找出赢得至少 15场比赛的巴西和奥地利赛手  
 static void Filtering()  
 {  
     var racers = from r in Formula1.GetChampions()  
                  where r.Wins > 15 && (r.Country == "Brazil" || r.Country == "Austria")  
                  select r;  
  
     foreach (var r in racers)  
     {  
         Console.WriteLine("{0:A}", r);  
     }  
  
 }  
  
 //取消Linq并行操作  
 static void Cancellation()  
 {  
     const int arraySize = 100000000;  
     var data = new int[arraySize];  
     var r = new Random();  
     for (int i = 0; i < arraySize; i++)  
     {  
         data[i] = r.Next(40);  
     }  
  
     var cts = new CancellationTokenSource();  
  
     new Thread(() =>  
         {  
             try  
             {  
                 var sum = (from x in data.AsParallel().WithCancellation(cts.Token)  
                            where x < 80  
                            select x).Sum();  
                 Console.WriteLine("query finished, sum: {0}", sum);  
             }  
             catch (OperationCanceledException ex)  
             {  
                 Console.WriteLine(ex.Message);  
             }  
         }).Start();  
  
  
     Console.WriteLine("query started");  
     Console.Write("cancel? ");  
     int input = Console.Read();  
     if (input == 'Y' || input == 'y')  
     {  
         // cancel!  
         cts.Cancel();  
     }  
 }  
  
 //Linq 并行操作  
 static void IntroParallel()  
 {  
     const int arraySize = 100000000;  
     var data = new int[arraySize];  
     var r = new Random();  
     for (int i = 0; i < arraySize; i++)  
  
data[i] = r.Next(40);  
  
     Stopwatch watch = new Stopwatch();  
     watch.Start();  
       
     var q1 = (from x in Partitioner.Create(data).AsParallel()  
               where x < 80  
              select x).Sum();  
     watch.Stop();  
     Console.WriteLine(watch.ElapsedMilliseconds);  
 }