tap
tap

Reputation: 553

Filtering a List using lambda

I have an object which has properties ID, brandID, brandName, NumPages, and Type.

i need to show the top 5 brands by numPage size, a brand may have multiple IDs, so I need to group by brand

 listing.OrderByDescending(o => o.numPage).GroupBy(o=> o.brandName).Take(5).ToList();

is alone the lines of what im looking for but this is not valid code.

Upvotes: 0

Views: 331

Answers (2)

Giorgio Minardi
Giorgio Minardi

Reputation: 2775

just tried and it works:

public class Listing
{
    public int ID { get; set; }
    public int BrandID { get; set; }
    public string BrandName { get; set; }
    public int NumPages { get; set; }
    public Type Type { get; set; }    
}

Here the filtering

Listing listing1 = new Listing() { NumPages = 2, BrandName = "xx" };
Listing listing2 = new Listing() { NumPages = 2, BrandName = "xx" };
Listing listing3 = new Listing() { NumPages = 2, BrandName = "xx" };
Listing listing4 = new Listing() { NumPages = 3, BrandName = "xxxxx" };

List<Listing> allListings = new List<Listing>() { listing1, listing2, listing3, listing4 };

var result = allListings.OrderByDescending(x => x.NumPages).GroupBy(x => x.BrandName).Take(5);

Upvotes: 0

JaredPar
JaredPar

Reputation: 754545

It sounds like a given brand name may have several ID's and that you want the top 5 brand's sorted by numPage. Is that correct

If so try the following

var query = listing
  .GroupBy(x => x.brandName)
  .OrderByDescending(brands => brands.Sum(x => x.numPage))
  .Select(x => x.Key)
  .Take(5);

Note: After the GroupBy operation you're now passing around a collection of the brand objects instead of single ones. Hence to order by the numPage we need to sum it for all of the brand objects in the group. The .Select(x => x.Key) will select back out the original brandName on which the group is based

Upvotes: 2

Related Questions