public static List <Racer> TraditionalQuery() { List <Racer> racers = new List <Racer>(Formula1.GetChampions()); List <Racer> brazilRacers = racers.FindAll(delegate(Racer r) { return(r.Country == "Brazil"); }); brazilRacers.Sort( delegate(Racer r1, Racer r2) { return(r2.Wins.CompareTo(r1.Wins)); }); return(brazilRacers); }
public static IEnumerable <Racer> LambdaExpressions() { IEnumerable <Racer> brazilChampions = Formula1.GetChampions(). Where(r => r.Country == "Brazil"). OrderByDescending(r => r.Wins). Select(r => r); /* * foreach (Racer r in brazilChampions) * { * * Console.WriteLine("{0:A}, r"); * } */ return(brazilChampions); }
public static IEnumerable <Racer> LinqQuery() { var query = from r in Formula1.GetChampions() where r.Country == "Brazil" orderby r.Wins descending select r; //Filtering var races = from r in Formula1.GetChampions() where r.Wins > 15 && (r.Country == "Brazil" || r.Country == "Austria") select r; //Filtering with lambda expression var racers = Formula1.GetChampions().Where(r => r.Wins > 15 && (r.Country == "Brazil" || r.Country == "Austria")).Select(r => r); //Filtering with index var racerss = Formula1.GetChampions().Where((r, index) => r.LastName.StartsWith("A") && index % 2 != 0); //Type Filtering object[] data = { "one", 2, 3, "four", "five", 6 }; var myquery = data.OfType <string>(); foreach (var s in query) { Console.WriteLine(s); } //Compound form var ferrariDrivers = from r in Formula1.GetChampions() from c in r.Cars where c == "Ferrari" orderby r.LastName select r.FirstName + " " + r.LastName; //SelectMany var ferrariDriversMany = Formula1.GetChampions(). SelectMany(r => r.Cars, (r, c) => new { Racer = r, Car = c }). Where(r => r.Car == "Ferrari"). OrderBy(r => r.Racer.LastName). Select(r => r.Racer.FirstName + " " + r.Racer.LastName); //Sorting Linq var racersSortingLinq = from r in Formula1.GetChampions() where r.Country == "Brazil" orderby r.Wins descending select r; //Sorting Lamba (extansion methods) var racersSortingLambda = Formula1.GetChampions(). Where(r => r.Country == "Brazil"). OrderByDescending(r => r.Wins). Select(r => r); //Take var racersTake = (from r in Formula1.GetChampions() orderby r.Country, r.LastName, r.FirstName select r).Take(10); //Take with extension methods Lambda var racersTakeLambda = Formula1.GetChampions(). OrderBy(r => r.Country). ThenBy(r => r.LastName). ThenBy(r => r.FirstName). Take(10); //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() }; //Gouping with extension methods Lambda var countriesLambda = Formula1.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() }); return(racersTake); }