Ross
Ross

Reputation: 373

Linq Count based on Boolean

I'm trying to get a linq query running which I can't get right.

I have a list of a custom class called Occurrences, this class has two properties Code as String and Negative as Boolean. I am trying to get the net total of Code (group by Code) so this would be a count of Code where Negative = False (All positive), subtract a count of Code where Negative = True (All negative). There is no quantity in the Occurrences class, each occurrence counts as 1 negative or positive.

I tried to do this in 3 separate queries which did not work, ideally I would like to do this in 1 query.

Please let me know if you need a better explanation or if I am unclear.

Edit: Sample input/output

Input:

Code       Negative
-------------------
123        True
123        True
123        False
456        True
456        True
456        True
789        False
789        False

Output:

Code       Count
----------------
123        -1
456        -3
789        +2

Upvotes: 1

Views: 1633

Answers (3)

Anthony D. Green
Anthony D. Green

Reputation: 26

Dim netTotal = From o In Occurrences
               Group By o.Code
               Into Sum(If(o.Negative, -1, 1))

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

You can try a direct translation of your explanation to LINQ, which would look like this:

var totalByCode = data
    .GroupBy(item => item.Code)
    .ToDictionary(
         g => g.Key
    ,    g => g.Count(o => !o.Negative) - g.Count(o => o.Negative)
    );

This produces a Dictionary<string,int> that maps the Code to the corresponding count computed as the difference between non-negative and negative occurrences.

Upvotes: 1

Amy B
Amy B

Reputation: 110071

from item in data
group item by item.Code into g
select new { Code = g.Key, Count = g.Sum(x => x.Negative ? -1 : 1) }

Upvotes: 2

Related Questions