Home > Blockchain >  Linq group by performance
Linq group by performance

Time:01-31

I have a list of post objects. Each post object has a car property and each car object has a brand property. I am trying to find total number of posts for a particular brand, for this I am using the following code

var grp = posts.Where(t=> !t.Car.Brand.Name.Equals("Test"))
                .Select(t=> new Brand
                {
                    BrandId = t.Car.Brand.Id,
                    Name = t.Car.Brand.Name,
                    Url = t.Car.Brand.Url,
                })
                .GroupBy(t => t.BrandId)
                .Select(t=> new Brand
                {
                    BrandId = t.First().BrandId,
                    Name = t.First().Name,
                    Url = t.First().Url,
                    Count = t.Count()
                }).OrderByDescending(t=>t.Count).ToList();

This code works but it is a bit slow, any suggestions to improve performance?

CodePudding user response:

Using First() on grouping result dramaticallly decrease perfromance. Up to EF Core 6 it will thtow exception that this query is not translatablke. If you want to write performant queries always think in SQL way: grouping can return only grouping keys and aggregation result, other quirks are slow, even they are translatable to the SQL.

var grp = posts
    .Where(t => !t.Car.Brand.Name.Equals("Test"))
    .Select(t => new Brand
    {
        BrandId = t.Car.Brand.Id,
        Name = t.Car.Brand.Name,
        Url = t.Car.Brand.Url,
    })
    .GroupBy(t => t)
    .Select(t => new Brand
    {
        BrandId = t.Key.BrandId,
        Name = t.Key.Name,
        Url = t.Key.Url,
        Count = t.Count()
    })
    .OrderByDescending(t => t.Count)
    .ToList();
  • Related