Peter Bridger
Peter Bridger

Reputation: 9323

LINQ: Count number of true booleans in multiple columns

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

Answers (3)

AxelEckenberger
AxelEckenberger

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

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120927

You can do it like so:

var emailCount = yourDataContext.YourTable.Count(r => r.HasEmail);

etc.

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

var mobileCount = myTable.Count(user => user.MobileAvailable);

And so on for the other counts.

Upvotes: 1

Related Questions