Reputation: 35703
I have a DBSet<User>
of users. Each User has a DBSet<Activity>
of activities. Each activity itself has one or no Category with a name.
public class User
{
[...]
DBSet<Activity> activity {get;set;}
}
public class Activity
{
[...]
Category category{get;set;}
}
public class Category
{
[...]
string Name {get;set;}
}
Now i want to have a List of all users sorted by the number of occurrences of a given category name in activites. In other words: I want a list of users ordered by the number of his activities in a category. How can i do that with LINQ (lambda expressions)?
DBSet<User> users;
string cat="myCategory";
var usersByCategoryActivity = users.OrderByDescending(???);
Upvotes: 1
Views: 92
Reputation: 5018
This should work for you:
string cat="myCategory";
DBSet<User> users;
var usersByCategory = users
.OrderBy(e=> e.activity.Count(a => a.Categories.Name.Contains(cat)));
Upvotes: 3
Reputation: 17058
Something like that:
DBSet<User> users;
string cat = "myCategory";
var usersByCategoryActivity = users
.OrderByDescending(u => u.Activities
.Where(a => a.Categories.Select(c => c.Name)
.Contains(cat)
.Count()
);
If you look inside the query first, it retrieves all the activities which contains the given category. It count it all for a user, and order by that.
I'm not sure this is what you need, but your description is not precise, and there is not a samples of data. So it maybe be good enough. Maybe not.
Upvotes: 1
Reputation: 6445
Maybe
var usersByCategory = users.ToList().OrderBy(e=>e.activity.Count());
Upvotes: 0