Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 892
Peter Bridger Avatar asked Oct 18 '25 13:10

Peter Bridger


2 Answers

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.

like image 87
AxelEckenberger Avatar answered Oct 20 '25 03:10

AxelEckenberger


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

And so on for the other counts.

like image 38
Yuriy Faktorovich Avatar answered Oct 20 '25 03:10

Yuriy Faktorovich