简体   繁体   English

LINQ-具有分组吗?

[英]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. 在T-SQL中,这是我的查询,非常好。 Need similar in LINQ. 在LINQ中需要类似的东西。 For example in above it will give both rows for ABC & XXX. 例如,在上面,它将为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 但是我认为你想要不是最小和最大的any()

  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. 这将检查任何小于0的值和大于0的任何值。它将短路,因此它没有遍历整个列表,因此应使其速度更快。

或这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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