Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a table like below
Bit	AId
true	1
false	1
false	2
true	2
true	1
false	3
true	1
false	3
false	1
true	2
true	1
true	3
false	3
true	2

suppose corresponding entity for above table is A.

I want a query entityframework method based that it subtract count of true from count of false for every unique AId. like below
Bit    AId
2      1
2      2
-2     3
Posted
Updated 28-Jul-14 6:15am
v2

1 solution

How about something like this:
C#
IDictionary<int, int> result = context.A
    .GroupBy(a => a.AId, (AId, list) => new 
    { 
        AId, 
        TrueCount = list.Count(i => i.Bit), 
        FalseCount = list.Count(i => !i.Bit) 
    })
    .ToDictionary(x => x.AId, x => x.TrueCount - x.FalseCount)
;


Edit: Dictionaries do not preserve the order of the elements. If you want to use OrderBy, you'll need to use a difference collection type.

C#
var result = context.A
    .GroupBy(a => a.AId, (AId, list) => new
    {
        AId,
        Count = list.Count(i => i.Bit) - list.Count(i => !i.Bit)
    })
    .OrderBy(x => x.Count)
    .ToList()
;

// "result" now contains a sorted list of anonymous types,
// each of which has the properties "AId" and "Count".
 
Share this answer
 
v2
Comments
kave2011 28-Jul-14 13:03pm    
I want to use orderby for value of result but I get error.
Richard Deeming 28-Jul-14 13:10pm    
Dictionaries do not preserve the order of their elements. You'll need to use a different collection type. I've updated my answer with an example.
kave2011 28-Jul-14 13:18pm    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900