当前位置:网站首页>LINQ query (2)

LINQ query (2)

2022-06-24 08:14:00 flysh05

1. Type filtering

  object[] data = { "one", 2, 4, "Four", "five", 6 };

    var query = data.OfType<string>();

    foreach (var s in query)

    {

        Console.WriteLine(s);

    }

Output : “one”, “Four”, “five”

2. Composite query

var ferrariDrivers = **from** r in Formula1.GetChampions()

                                **from** c in r.Cars

                                where c == "Ferrari"

                                orderby r.LastName

                                select r.FirstName + " " + r.LastName;

Compound query using method

var ferrariDrivers = 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);

3. 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()

                            };

Use method grouping

var countries = 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()

                });

Grouping of nested objects

var countries = from r in Formula1.GetChampions()

                            group r by r.Country into g

                            let count = g.Count()

                            orderby count descending, g.Key

                            where count >= 2

                            select new

                            {
    

                                Country = g.Key,

                                Count = count,

                                Racers = from r1 in g

                                        orderby r1.LastName

                                        select r1.FirstName + " " + r1.LastName

                            };
原网站

版权声明
本文为[flysh05]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240410179705.html