Reputation: 6866
I am trying to create a linq
query to do the following:
So far I have come up with the below:
var query = context.Users;
List<Users> users = query.ToList();
int totalUsers = users.Count;
int officialUsers = users.Where(s => s.IsOfficialUser).ToList().Count;
int nonOfficialUsers = users.Where(s => !s.IsOfficialUser).ToList().Count;
I'm not sure how much performance impact will happen by me calling .ToList()
numerous times. So I was hoping is there a way to optimize the query or am I on the right track?
Upvotes: 4
Views: 89
Reputation: 65534
One easy optimisation:
int totalUsers = users.Count;
int officialUsers = users.Where(s => s.IsOfficialUser).ToList().Count;
int nonOfficialUsers = totalUsers - officialUsers;
Once this line of code is run List<Users> users = query.ToList();
the query is immediately executed.
You don't need the ToList()
again after that, see here:
int totalUsers = users.Count;
int officialUsers = users.Count(s => s.IsOfficialUser);
int nonOfficialUsers = totalUsers - officialUsers;
Upvotes: 3
Reputation: 29006
What about this method?
IsOfficialUser
which gives you two collections of nonOfficialUsers
and officialUsers
right?Now try this Example:
var groupedUsers = users.GroupBy(x => x.IsOfficialUser).ToDictionary(g => g.Key, g=>g.Count());
int officialUsers = groupedUsers[true];
int nonOfficialUsers = groupedUsers[false];
int totalUsers = nonOfficialUsers + officialUsers;
Upvotes: 0
Reputation: 82267
Using .ToList
on a materialized list will only impact the amount of memory required. While this can technically have a performance hit, it is unlikely unless you have millions of users; in which case, you would honestly probably have the server RAM available anyway.
The .ToList
certainly isn't required though. All you are needing to do is count the differentiation here, so you can skip the ToList, and the Where (as Count accepts a Func)
int officialUsers = users.Count(s => s.IsOfficialUser);
int nonOfficialUsers = users.Count(s => !s.IsOfficialUser);
Upvotes: 3