LINQ: number of instances of true boolean elements in multiple columns

I use LINQ to SQL to speed up the delivery of a project with which it really helps. However, I struggle with a few things that I'm used to doing with manual SQL.

I have a LINQ collection containing three columns, each of which contains a boolean representing the availability of an email, mobile phone, or address.

I want to write a LINQ query to give me the number of truths for each column , so the number of rows in the email column is true (and the same for the other two columns)

+3
source share
3 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;
 }
);

xhas a type Resultand contains aggregated information. It can also be used for more complex aggregations.

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

And so on for other calculations.

+1
source

You can do it like this:

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

and etc.

+1
source

Source: https://habr.com/ru/post/1736487/


All Articles