Reputation: 9323
I'm using LINQ to SQL to speed up delivery of a project, which it's really helping with. However I'm struggling with a few things I'm used to doing with manual SQL.
I have a LINQ collection containing three columns, each containing a boolean value representing whether an e-mail, mobile or address is availble.
I want to write a LINQ query to give me an count of trues for each column, so how many rows in the e-mail column are set to true (and the same for the other two columns)
Upvotes: 4
Views: 4556
Reputation: 16926
If you need a single object containing the results:
var result = new {
HasEmailCount = list.Count(x => x.HasEmail),
HasMobileCount = list.Count(x => x.HasMobile),
HasAddressCount = list.Count(x => x.HasAddress)
};
Or using the aggregate function:
class Result
{
public int HasEmail;
public int HasAddress;
public int HasMobile;
}
var x = data.Aggregate(
new Result(),
(res, next) => {
res.HasEmail += (next.HasEmail ? 0 : 1);
res.HasAddress += (next.HasAddress ? 0 : 1);
res.HasMobile += (next.HasMobile ? 0 : 1);
return res;
}
);
x
is of Type Result
and contains the aggregated information. This can also be used for more compelx aggregations.
Upvotes: 5
Reputation: 120927
You can do it like so:
var emailCount = yourDataContext.YourTable.Count(r => r.HasEmail);
etc.
Upvotes: 1
Reputation: 68667
var mobileCount = myTable.Count(user => user.MobileAvailable);
And so on for the other counts.
Upvotes: 1