假設我有這張表:
| 圖片 | 周長 |
|---|---|
| 一個 | 1個 |
| b | 1個 |
| b | 2個 |
| d | 3個 |
| 電子 | 1個 |
我想回傳僅與一個周長相關的影像。
預期結果將是影像“a、d、e”,因為影像“b”與周長“1”和“2”有關系。
目的是洗掉周邊時洗掉相關影像。但如果它鏈接到另一個周邊,我無法將其洗掉。
如何使用 LINQ 撰寫此查詢?
我認為它會是這樣的:
SELECT "ImageId"
WHERE "PerimeterId" = PerimeterId IN
(
SELECT "ImageId"
GROUP BY "ImageId"
HAVING COUNT("PerimeterId") = 1
)
但我不知道如何將其轉換為 LINQ。
uj5u.com熱心網友回復:
你可以使用一個NOT EXISTS
var query = dbo.Table
.Where(t => !dbo.Table.Any(t2 => t.Image = t.Image && t.Perimeter != t2.Perimeter));
uj5u.com熱心網友回復:
您可以輕松地將其調整為僅選擇影像部分。但是,如果您來自 SQL,考慮基于“HAVING()”組計算的“選擇行”,那么您將需要查看 .SelectMany() LINQ 方法。這使您可以“將磁區的資料重新組合在一起”。雖然您的需求只是回傳“每組中的一個”,但很容易看出可以在哪里進行調整。這可以在 SSDT 2015 的“C# 互動視窗”中運行:
struct imagePerimeter { //this might be whatever object type it is for you...
public string Image { get; set; } //a,b,b,d,e
public int Perimeter { get; set; } //1,1,2,3,1
}
Func<string, int, imagePerimeter> newIP = (i, p) => new imagePerimeter() { Image = i, Perimeter = p };
List<imagePerimeter> results = new List<imagePerimeter>() { {newIP("a",1) }
,{newIP("b",1) }
,{newIP("b",2) }
,{newIP("d",3) }
,{newIP("e",1) } };
Func<imagePerimeter, string> ipImage = (ip) => ip.Image; //the Func's "ipImage" and "newIP" could just be inlined into LINQ, but it helps to see and debug at times IMO.
var imagesWithOnePerimeter = results.GroupBy<imagePerimeter, string>(ipImage) //even in SQL, the "GROUP BY" conceptually comes first, in LINQ, it comes first in code too!
.Select(grp => new { Image = grp.Key, PerimeterCount = grp.Count(), Details = grp }) //there's probably a more technical term, but notice how we "carry forward" the original reference to [grp]
.Where(subTotals => subTotals.PerimeterCount == 1)
.SelectMany(filtered => filtered.Details.AsEnumerable())
.ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535346.html
標籤:C#数据库数据库林克
上一篇:找到連續區間并給出一個id
