Search code examples
c#linq-to-sqlentity-framework-4

Linq OrderBy Count In linked list


I've been struggling for a while now. All I am trying to do is OrderBy a list of records by the Count() of a 3rd child in the relationship tree. I will try and draw the 3 tables involved below, sorry if I don't use the stackoverflow standards:

Websites ----> Roles ----> Permissions

In words, a website can have more than 1 Roles, a role can have more than 1 Permissions. So it's a 1-to-many.

When I try something like:

List<Website> websites = Model.WebsiteOptions.OrderBy( o => o.Roles.OrderBy( r => r.RolePermissions.Count ) ).ToList();

I get an error that's clear enough:

At least one object must implement IComparable.

but I still don't know how I can either way order Websites by the number of Permissions each Role has...What I want is for websites that have Roles with the most Permissions to come first.

Please does anyone know or show me some guidance?

Thanks in advance.


Solution

  • You get that error because in your OrderBy you should specify how to order the collection - meaning supplying an object that implements IComparable.

    In your implementation you are actually supplying another collection which is sorted (this is irrelevant though). An IEnumerable<T> doesn't implement IComparable<IEnumerable<T>> but just IComparable<T> - it can compare 2 "simple" items but not two collections. (Will you do it by number of elements?.. biggest element? It is generic so what does biggest even mean.....)

    Try something like:

    List<Website> websites = Model.WebsiteOptions.OrderBy( o => o.Roles.Max( r => r.RolePermissions.Count ) ).ToList();
    

    This will order your Websites by the option that has the highest RolePermissions count