简体   繁体   中英

LINQ - Group By with Having?

I have a db table which is having data like below.

Name   Tool   Security  QUANTITY    PRICE
  ABC      ML      XXX     100         50      
  ABC      DB      XXX    -50          50      
  XYZ      CS      YYY     30          30

My requirement is to group the name and security and pick only that record which is having both negative and positive quantity. In T-SQL this is my query which is perfectly fine. Need similar in LINQ. For example in above it will give both rows for ABC & XXX.

select t1.* from MyTable as t1
inner join
(
    select Name,Security  from MyTable 
    group by Name, Security  
    HAVING min(Quantity)<0 and max(Quantity)>0
) as t2 on t1.Name=t2.Name and t1.Security  =t2.Security  

This is my inner query but it's not working.

var Positions = from r in lstpositions
                                  group r by new { r.Name, r.Security} into grp
                                  where grp.Min(x => x.Quantity<0) && grp.Max(x => x.Quantity >0)
                                  select grp;

Any thoughts on this ?

The reason your query does not work is because you taking the min of the result of the comparison.

However I think you want any() not min and max

  where grp.Any(x => x.Quantity<0) && grp.Any(x => x.Quantity >0)

This will check for any value below 0 and any value above 0. It will short circuit so it does not have traverse the entire list which should make it faster.

或这个

where grp.Min(x => x.Quantity) < 0 && grp.Max(x => x.Quantity) > 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM