private static void SelectMany2() { // flatten the year list to return a list of all racers and positions in the championship var racers = Formula1.GetChampionships() .SelectMany(cs => new List <dynamic>() { new { Year = cs.Year, Position = 1, Name = cs.First }, new { Year = cs.Year, Position = 2, Name = cs.Second }, new { Year = cs.Year, Position = 3, Name = cs.Third } }); foreach (var s in racers) { Console.WriteLine(s); } }
private static void CombineRacers() { var q = from r in Formula1.GetChampions() join r2 in Formula1.GetChampionships().GetRacerInfo() on new { FirstName = r.FirstName, LastName = r.LastName } equals new { FirstName = r2.FirstName, LastName = r2.LastName } into yearResults select new { FirstName = r.FirstName, LastName = r.LastName, Wins = r.Wins, Starts = r.Starts, Results = yearResults }; foreach (var item in q) { Console.WriteLine("{0} {1}", item.FirstName, item.LastName); foreach (var item2 in item.Results) { Console.WriteLine("{0} {1}", item2.Year, item2.Position); } } }
static void GroupJoinWithMethods() { var racers = Formula1.GetChampionships() .SelectMany(cs => new List <(int Year, int Position, string FirstName, string LastName)> { (cs.Year, Position: 1, FirstName: cs.First.FirstName(), LastName: cs.First.LastName()), (cs.Year, Position: 2, FirstName: cs.Second.FirstName(), LastName: cs.Second.LastName()), (cs.Year, Position: 3, FirstName: cs.Third.FirstName(), LastName: cs.Third.LastName()) }); var q = Formula1.GetChampions() .GroupJoin(racers, r1 => (r1.FirstName, r1.LastName), r2 => (r2.FirstName, r2.LastName), (r1, r2s) => (r1.FirstName, r1.LastName, r1.Wins, r1.Starts, Results: r2s)); foreach (var r in q) { Console.WriteLine($"{r.FirstName} {r.LastName}"); foreach (var results in r.Results) { Console.WriteLine($"{results.Year} {results.Position}"); } } }
public static void Except() { Console.WriteLine("Show the list of Formula 1 drives that have been in the top 3 but never a world champion"); var racers = Formula1.GetChampionships().SelectMany(cs => new List <RacerInfo>() { new RacerInfo(cs.Year, 1, cs.First.FirstName(), cs.First.LastName()), new RacerInfo(cs.Year, 2, cs.Second.FirstName(), cs.Second.LastName()), new RacerInfo(cs.Year, 3, cs.Third.FirstName(), cs.Third.LastName()) }); var nonChampions = racers.Select(r => new { r.FirstName, r.LastName }).Except(Formula1.GetChampions().Select(r => new { r.FirstName, r.LastName })); foreach (var r in nonChampions) { Console.WriteLine($"{r.FirstName} {r.LastName}"); } }
private static void CombineRacers() { var q = from r in Formula1.GetChampions() join r2 in Formula1.GetChampionships().GetRacerInfo() on ( FirstName: r.FirstName, LastName: r.LastName ) equals ( FirstName: r2.FirstName, LastName: r2.LastName ) into yearResults select new { FirstName = r.FirstName, LastName = r.LastName, Wins = r.Wins, Starts = r.Starts, Results = yearResults }; foreach (var item in q) { WriteLine($"{item.FirstName} {item.LastName}"); foreach (var item2 in item.Results) { WriteLine($"{item2.Year} {item2.Position}"); } } }
static void GroupJoin2() { var racers = Formula1.GetChampionships() .SelectMany(cs => new List <RacerInfo>() { new RacerInfo { Year = cs.Year, Position = 1, FirstName = cs.First.FirstName(), LastName = cs.First.LastName() }, new RacerInfo { Year = cs.Year, Position = 2, FirstName = cs.Second.FirstName(), LastName = cs.Second.LastName() }, new RacerInfo { Year = cs.Year, Position = 3, FirstName = cs.Third.FirstName(), LastName = cs.Third.LastName() } }); var q = (from r in Formula1.GetChampions() join r2 in racers on new { FirstName = r.FirstName, LastName = r.LastName } equals new { FirstName = r2.FirstName, LastName = r2.LastName } into yearResults select new { FirstName = r.FirstName, LastName = r.LastName, Wins = r.Wins, Starts = r.Starts, Results = yearResults }); foreach (var r in q) { Console.WriteLine("{0} {1}", r.FirstName, r.LastName); foreach (var results in r.Results) { Console.WriteLine("{0} {1}", results.Year, results.Position); } } }
static void GroupJoinWithMethodsAndNoTuples() { var racers = Formula1.GetChampionships() .SelectMany(cs => new List <RacerInfo>() { new RacerInfo { Year = cs.Year, Position = 1, FirstName = cs.First.FirstName(), LastName = cs.First.LastName() }, new RacerInfo { Year = cs.Year, Position = 2, FirstName = cs.Second.FirstName(), LastName = cs.Second.LastName() }, new RacerInfo { Year = cs.Year, Position = 3, FirstName = cs.Third.FirstName(), LastName = cs.Third.LastName() } }); var q = Formula1.GetChampions() .GroupJoin(racers, r1 => new { r1.FirstName, r1.LastName }, // outer key selector r2 => new { r2.FirstName, r2.LastName }, // inner key selector (r1, r2s) => new { r1.FirstName, r1.LastName, r1.Wins, r1.Starts, Results = r2s }); // result selector foreach (var r in q) { Console.WriteLine($"{r.FirstName} {r.LastName}"); foreach (var results in r.Results) { Console.WriteLine($"{results.Year} {results.Position}"); } } }
private static void Except() { var racers = Formula1.GetChampionships().SelectMany(cs => new List <RacerInfo>() { new RacerInfo { Year = cs.Year, Position = 1, FirstName = cs.First.FirstName(), LastName = cs.First.LastName() }, new RacerInfo { Year = cs.Year, Position = 2, FirstName = cs.Second.FirstName(), LastName = cs.Second.LastName() }, new RacerInfo { Year = cs.Year, Position = 3, FirstName = cs.Third.FirstName(), LastName = cs.Third.LastName() } }); var nonChampions = racers.Select(r => new { FirstName = r.FirstName, LastName = r.LastName }).Except(Formula1.GetChampions().Select(r => new { FirstName = r.FirstName, LastName = r.LastName })); foreach (var r in nonChampions) { Console.WriteLine("{0} {1}", r.FirstName, r.LastName); } }
static void GroupJoin() { var racers = from cs in Formula1.GetChampionships() from r in new List <(int Year, int Position, string FirstName, string LastName)>() { (cs.Year, Position : 1, FirstName : cs.First.FirstName(), LastName : cs.First.LastName()), (cs.Year, Position : 2, FirstName : cs.Second.FirstName(), LastName : cs.Second.LastName()), (cs.Year, Position : 3, FirstName : cs.Third.FirstName(), LastName : cs.Third.LastName()) } select r; var q = (from r in Formula1.GetChampions() join r2 in racers on ( r.FirstName, r.LastName ) equals ( r2.FirstName, r2.LastName ) into yearResults select ( r.FirstName, r.LastName, r.Wins, r.Starts, Results: yearResults )); foreach (var r in q) { Console.WriteLine($"{r.FirstName} {r.LastName}"); foreach (var results in r.Results) { Console.WriteLine($"\t{results.Year} {results.Position}"); } } }
// 4.操作符实例 static void OpteratorSampleMethod() { // 1.使用where子句,可以合并多个表达式 var racers = from r in Formula1.GetChampions() where r.Wins > 15 && (r.Country == "Brazil" || r.Country == "Austria") select r; DisplayRacers(racers); // 2.使用索引查询 racers = Formula1.GetChampions(). Where((r, index) => r.LastName.StartsWith("A") && index % 2 != 0); DisplayRacers(racers); // 3.类型筛选 Console.WriteLine("类型筛选"); object[] data = { "one", 2, 3, "four", "five", 6 }; var query = data.OfType <string>(); foreach (var s in query) { Console.WriteLine(s); } Console.WriteLine(); // 4.复合的from子句 Console.WriteLine("复合的from子句"); var ferrariDrivers = from r in Formula1.GetChampions() from c in r.Cars where c == "Ferrari" orderby r.LastName select r.FirstName + " " + r.LastName; DisplayRacers(ferrariDrivers); // 5.排序 Console.WriteLine("排序"); racers = (from r in Formula1.GetChampions() orderby r.Country, r.LastName, r.FirstName select r).Take(10); DisplayRacers(racers); // 6.分组 Console.WriteLine("分组"); 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); } Console.WriteLine(); // 7.对嵌套的对象分组 Console.WriteLine("对嵌套内的对象分组"); var mcountries = 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 mcountries) { Console.WriteLine("{0,-10} {1}", item.Country, item.Count); foreach (var name in item.Racers) { Console.WriteLine("{0}: ", name); } Console.WriteLine(); } // 8.内连接:使用join子句可以根据特定的条件合并两个数据源,但之前要获得两个连接的列表 var racers1 = from r in Formula1.GetChampions() from y in r.Years select new { Year = y, Name = r.FirstName + " " + r.LastName }; var teams = from t in Formula1.GetContructorChampions() from y in t.Years select new { Year = y, Name = t.Name }; var racersAndTeams = from r in racers1 join t in teams on r.Year equals t.Year select new { r.Year, Champion = r.Name, Constructor = t.Name }; Console.WriteLine("Year World Champion\t Constructor Title"); foreach (var item in racersAndTeams) { Console.WriteLine("{0}: {1,-20} {2}", item.Year, item.Champion, item.Constructor); } Console.WriteLine(); // 9.组连接 Console.WriteLine("组连接"); var racers2 = Formula1.GetChampionships() .SelectMany(cs => new List <RacerInfo>() { new RacerInfo { Year = cs.Year, Position = 1, FirstName = cs.First.FirstName(), LastName = cs.First.LastName() }, new RacerInfo { Year = cs.Year, Position = 2, FirstName = cs.Second.FirstName(), LastName = cs.Second.LastName() }, new RacerInfo { Year = cs.Year, Position = 3, FirstName = cs.Third.FirstName(), LastName = cs.Third.LastName() } }); var q = (from r in Formula1.GetChampions() join r2 in racers2 on new { FirstName = r.FirstName, LastName = r.LastName } equals new { FirstName = r2.FirstName, LastName = r2.LastName } into yearResults select new { FirstName = r.FirstName, LastName = r.LastName, Wins = r.Wins, Starts = r.Starts, Results = yearResults }); foreach (var r in q) { Console.WriteLine("{0} {1}", r.FirstName, r.LastName); foreach (var results in r.Results) { Console.WriteLine("{0} {1}", results.Year, results.Position); } } // 10.集合操作 // 定义委托 Console.WriteLine("集合操作"); Func <string, IEnumerable <Racer> > racerByCar = car => from r in Formula1.GetChampions() from c in r.Cars where c == car orderby r.LastName select r; Console.WriteLine("World champion with ferrati and McLaren"); foreach (var racer in racerByCar("Ferrari").Intersect(racerByCar("McLaren"))) { Console.WriteLine(racer); } // 11.合并 Console.WriteLine("合并操作"); var racerName = 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 racers3 = racerName.Zip(racerNamesAndStarts, (first, second) => first.Name + ", starts" + second); foreach (var r in racers) { Console.WriteLine(r); } Console.WriteLine(); }
public static void Main(string[] args) { Cons.WriteLine($"Start the LINQ Stuff.....{args?[0]}"); var champs = Formula1.GetChampions(); var q1 = from r in Formula1.GetChampions() where r.Country == "UK" orderby r.Wins descending select r; foreach (Racer r in q1) { Cons.WriteLine($"{r:A}"); } //Extension Method! Just another way to get at static classes! var s = "All"; s.Boots(); //Q1 using extensions methods to for show... var champs2 = new List <Racer>(Formula1.GetChampions()); IEnumerable <Racer> Brits = champs2.Where(c => c.Country == "UK").OrderBy(o => o.LastName) .Select(r => r); DeferredDemo.DeferredEx1(); //LINQ query examples var wins10plus = from r in champs2 where r.Wins >= 10 select r; var wins10Plus2 = Formula1.GetChampions().Where(r => r.Wins >= 10).Select(r => r).ToList(); //Example where one can't use LINQ and have to use the extension method. var r1 = champs2.Where((r, Index) => r.LastName.StartsWith("A") || Index % 2 != 0); //Type Filtering object[] data = { "One", 1, 2, 3, 4, "Five", "Six" }; var int1 = data.OfType <int>().OrderBy(n => n); foreach (var i in int1.Reverse()) { Cons.WriteLine($"{i}"); } //Compound froms var ferrariDrives = from r in Formula1.GetChampions() from c in r.Cars where c == "Ferrari" select r.LastName + " " + r.LastName + " => " + c; var Drives1950s = from r in Formula1.GetChampions() from y in r.Years where y >= 1950 && y <= 1959 orderby y select r.LastName + " " + r.LastName + " => " + y; //Using Exstensions var Drivers1960s = Formula1.GetChampions().SelectMany(r => r.Years, (r, y) => new { Racer = r, Year = y }) .Where(r => r.Year >= 1960 && r.Year <= 1969).OrderBy(r => r.Year).Select(r => r.Racer.LastName + " " + r.Racer.FirstName + " " + r.Year); //OrderBy and Take... var oRacers = (from r in Formula1.GetChampions() orderby r.Country, r.LastName, r.FirstName descending select r).Take(10); //And With Exrensions oRacers = Formula1.GetChampions().OrderBy(r => r.Wins).ThenBy(r => r.LastName) .ThenByDescending(r => r.FirstName).Take(10); //Now some grouping var gRacers = from r in Formula1.GetChampions() group r by r.Country into c orderby c.Key select c; var gRacers2 = from r in Formula1.GetChampions() group r by r.Country into c orderby c.Key, c.Count() descending where c.Count() >= 2 select new { Country = c.Key, Count = c.Count() }; //Grouping with Nested Objects basicaly c from gRacers var gRacers3 = from r in Formula1.GetChampions() group r by r.Country into c orderby c.Key, c.Count() descending where c.Count() >= 2 select new { Country = c.Key, Count = c.Count(), Racers = from r2 in c orderby r2.Wins select new { r2.LastName, r2.Wins } }; //Inner Joins var ijRacers = from r in Formula1.GetChampions() from y in r.Years select new { Year = y, Name = r.LastName + ", " + r.FirstName }; var ijTeams = from t in F1_Teams.GetConstructorChampions() from y in t.Years select new { Year = y, Name = t.Name }; var ijRacerAndTeam = (from r in ijRacers join t in ijTeams on r.Year equals t.Year orderby r.Year select new { r.Year, Champion = r.Name, Constructor = t.Name } ).Take(10); var loRacerAndTeam = (from r in ijRacers join t in ijTeams on r.Year equals t.Year into rt from a in rt.DefaultIfEmpty() orderby r.Year select new { r.Year, Champion = r.Name, Constructor = a == null ? "Not One": a.Name } ).Take(10); //Group Join Step 1 flattern! var gjRacers = Formula1.GetChampionships().SelectMany(c => new List <RacerInfo>() { new RacerInfo { Year = c.Year, Position = 1, FirstName = c.Champion.FirstName(), LastName = c.Champion.LastName() }, new RacerInfo { Year = c.Year, Position = 2, FirstName = c.Second.FirstName(), LastName = c.Second.LastName() }, new RacerInfo { Year = c.Year, Position = 3, FirstName = c.Third.FirstName(), LastName = c.Third.LastName() } }).ToArray(); //Step 2 Join var q = (from r in Formula1.GetChampions() join ts in gjRacers on new { FirstName = r.FirstName, LastName = r.LastName } equals new { FirstName = ts.FirstName, LastName = ts.LastName } into yrResults select new { FirstName = r.FirstName, LastName = r.LastName, Wins = r.Wins, Starts = r.Starts, Results = yrResults } ).ToArray(); //Using Set Operators //Using a static method var ferrariDrivers = GetDrives("Ferrari"); var mcLarebDrivers = GetDrives("McLaren"); //Better way to use delegates! Func <string, IEnumerable <Racer> > racersByCar = car => from r in Formula1.GetChampions() from c in r.Cars where c == car orderby r.LastName select r; foreach (var r in racersByCar("Ferrari").Intersect(racersByCar("McLaren"))) { Cons.WriteLine(r.LastName); } //Zip method! var rNames = from r in Formula1.GetChampions() where r.Country == "Italy" orderby r.Wins descending select new { Name = r.FirstName + "," + r.LastName }; var rNameStarts = from r in Formula1.GetChampions() where r.Country == "Italy" orderby r.Wins descending select new { LastName = r.LastName, Starts = r.Starts }; var zRacers = rNames.Zip(rNameStarts, (a, b) => a.Name + ", Starts: " + b.Starts); foreach (var a in zRacers) { Cons.WriteLine(a.ToString()); } //Why the selections and order are so important! rNameStarts = from r in Formula1.GetChampions() where r.Country == "UK" orderby r.Wins select new { LastName = r.LastName, Starts = r.Starts }; zRacers = rNames.Zip(rNameStarts, (a, b) => a.Name + ", Starts: " + b.Starts); foreach (var a in zRacers) { Cons.WriteLine(a.ToString()); } //Complete crap lol //Partitioning int pSize = 20; int nPages = (int)Math.Ceiling(Formula1.GetChampions().Count / (double)pSize); for (int p = 0; p < nPages; p++) { Cons.WriteLine($"Page {p+1} of {nPages}:"); var pR = (from r in Formula1.GetChampions() orderby r.LastName, r.FirstName select r.LastName + ", " + r.FirstName).Skip(p * pSize).Take(pSize); foreach (var r in pR) { Cons.WriteLine(r); } Cons.ReadKey(); } //Aggregate Operators Count, Sum, Min, Max, Average and Aggregate return single values. //Count var aQ1 = from r in Formula1.GetChampions() let nYears = r.Years.Count() orderby nYears descending, r.LastName, r.FirstName select new { Name = r.LastName, Initials = r.FirstName.Initials(), Years = nYears }; foreach (var r in aQ1) { Cons.WriteLine($"{r.Name}, {r.Initials} Wins = {r.Years}"); } //Sum var t1 = from c in from r in Formula1.GetChampions() group r by r.Country select new { Key1 = c.Key }; var aS1 = (from c in from r in Formula1.GetChampions() group r by r.Country into c select new { Country = c.Key, Wins = (from r2 in c select r2.Wins).Sum() } orderby c.Wins descending, c.Country select c).Take(5); //Conversion Operators var lRacers = (from r in Formula1.GetChampions() from c in r.Cars select new { Car = c, Racer = r } ).ToLookup(cr => cr.Car, cr => cr.Racer); var lr = lRacers["Williams"]; //Gives us a lookup of just Williams drives //Using the Cast method! var oList = new System.Collections.ArrayList(Formula1.GetChampions() as System.Collections.ICollection ?? throw new InvalidOperationException()); var q2 = from r in oList.Cast <Racer>() where r.Country == "USA" select r; //Not sure what this is doing but it must be good!!!! //Generation Operators var vRange = Enumerable.Range(1, 20); var vRange2 = Enumerable.Range(1, 20).Select(i => i > 1? (i > 2? i * 2: i): i); //Parallel LINQ Cons.WriteLine($"Loading large dataset, please wait."); var lsData = LargeSample().ToList(); var watch = new Stopwatch(); watch.Start(); var pRes = (from x in lsData.AsParallel() where Math.Log(x) < 4 select x ).Average(); watch.Stop(); Cons.WriteLine($"Parallel run: {watch.Elapsed}"); watch.Reset(); watch.Start(); var nRes = (from x in lsData where Math.Log(x) < 4 select x ).Average(); watch.Stop(); Cons.WriteLine($"Normal run: {watch.Elapsed}"); watch.Reset(); watch.Start(); var mpRes = lsData.AsParallel().Where(x => Math.Log(x) < 4).Select(x => x).Average(); watch.Stop(); Cons.WriteLine($"Working Average with Parallel run: {watch.Elapsed}"); //Parallel LINQ //Partitions watch.Reset(); watch.Start(); var ppRes = (from x in Partitioner.Create(lsData, true).AsParallel().WithDegreeOfParallelism(4) where Math.Log(x) < 4 select x ).Average(); watch.Stop(); Cons.WriteLine($"Average with Degree of Parallelism set to 4: {watch.Elapsed}"); watch.Reset(); watch.Start(); var ppRes2 = (from x in Partitioner.Create(lsData, true).AsParallel().WithDegreeOfParallelism(8) where Math.Log(x) < 4 select x ).Average(); watch.Stop(); Cons.WriteLine($"Avergare Degree of Parallelism set to 8: {watch.Elapsed}"); watch.Reset(); watch.Start(); //Partitions // Candellations and how to do it.... var cts = new CancellationTokenSource(); //From using System.Threading; Task.Factory.StartNew(() => { try { Cons.WriteLine(); Cons.WriteLine("Cancellable Query Started!"); var cRes = (from x in lsData.AsParallel().WithCancellation(cts.Token) where Math.Log(x) < 4 select x).Average(); Cons.WriteLine($"Query not cancelled result: {cRes}"); } catch (OperationCanceledException cex) { Cons.WriteLine(); Cons.Write($"Cancell message, {cex.Message}"); } }); Cons.WriteLine("Cancell Query!"); cts.Cancel(); //Cons.Write($"Cancel ?"); //string input = Cons.ReadLine(); //if (input.ToLower().Equals("y")) // cts.Cancel(); // Candellations and how to do it.... //Expression Trees //Expression Trees Cons.Write($"Press anykey to finish and close."); Cons.ReadKey(); }
static void GroupJoin() { var racers = from cs in Formula1.GetChampionships() from r in new List <RacerInfo>() { new RacerInfo { Year = cs.Year, Position = 1, FirstName = cs.First.FirstName(), LastName = cs.First.LastName() }, new RacerInfo { Year = cs.Year, Position = 2, FirstName = cs.Second.FirstName(), LastName = cs.Second.LastName() }, new RacerInfo { Year = cs.Year, Position = 3, FirstName = cs.Third.FirstName(), LastName = cs.Third.LastName() } } select r; var q = (from r in Formula1.GetChampions() join r2 in racers on new { r.FirstName, r.LastName } equals new { r2.FirstName, r2.LastName } into yearResults select new { r.FirstName, r.LastName, r.Wins, r.Starts, Results = yearResults }); foreach (var r in q) { Console.WriteLine($"{r.FirstName} {r.LastName}"); foreach (var results in r.Results) { Console.WriteLine($"\t{results.Year} {results.Position}"); } } }