0

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.

1
  • Why it is not being valid? Are you getting an error message or just not getting the wanted results. Commented Jan 14, 2012 at 0:18

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

15 Comments

An IGrouping doesn't have a numPage member, so that shouldn't compile.
@hvd I verified in Visual Studio that this compiles. One of my earlier versions had a typo but the current one should work
Yes, my comment was based on the .OrderByDescending(x => x.numPage.Sum()) which you've indeed fixed.
@hvd i think i get bitten by that mistake every time I hand role a groupby :(
i get an Arguement null exection and it's not valid code, I should mention instead of a var query, im doing this in a viewModel being called from return View(new viewModel(listing.GroupBy... but that shouldn't make a difference
|
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.