簡體   English   中英

LINQ-具有分組嗎?

[英]LINQ - Group By with Having?

我有一個數據庫表,其中包含如下數據。

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

我的要求是將名稱和安全性分組,並僅選擇具有負數和正數的記錄。 在T-SQL中,這是我的查詢,非常好。 在LINQ中需要類似的東西。 例如,在上面,它將為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  

這是我的內部查詢,但不起作用。

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()

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

這將檢查任何小於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