簡體   English   中英

在 linq 查詢中添加 Max 和 Average

[英]Add Max and Average in linq query

我在下面有一個 sql 查詢:

SELECT MAX(r.Suburb), AVG(s.Longitude) AS Longitude, AVG(s.Latitude) AS Latitude 
From CafeAddress r inner join Cafe s on s.CafeId = r.CafeId
WHERE r.Region = 'Sydney'

輸出:

Bankstown   174.759541622222    -36.8552809611111

查詢應該獲取該地區的所有郊區,例如悉尼是該地區,郊區將包括 Bankstown 等。

我將如何在下面的 linq 查詢中添加最大值和平均值? (區域 ID 是用戶輸入(字符串))

var region = from cafeAddress in _context.CafeAddress
                         join cafe in _context.Cafe on cafeAddress.CafeId equals cafe.CafeId
                         where cafeAddress.StateProvinceRegion == regionId
                         select new { StateProvinceRegion = cafeAddress.Suburb.Max(), cafe.Latitude,  cafe.Longitude };

我只能通過使用 group by 來做到這一點,但我試圖避免這種情況。

我認為這將變得相當接近:

var query =
    from cafeAddress in _context.CafeAddress
    join cafe in _context.Cafe on cafeAddress.CafeId equals cafe.CafeId
    where cafeAddress.StateProvinceRegion == regionId
    orderby cafeAddress.Suburb descending
    group new
    {
        cafeAddress.Suburb,
        cafe.Latitude,
        cafe.Longitude
    } by cafeAddress.StateProvinceRegion into g
    select new
    {
        StateProvinceRegion = g.First().Suburb,
        Latitude = g.Average(x => x.Latitude),
        Longitude = g.Average(x => x.Longitude),
    };

或者這個輕微的變體:

var query =
    from cafeAddress in _context.CafeAddress
    join cafe in _context.Cafe on cafeAddress.CafeId equals cafe.CafeId
    where cafeAddress.StateProvinceRegion == regionId
    orderby cafeAddress.Suburb descending
    group new
    {
        cafeAddress.Suburb,
        cafe.Latitude,
        cafe.Longitude
    } by cafeAddress.StateProvinceRegion into gs
    from g in gs.Take(1)
    select new
    {
        StateProvinceRegion = g.Suburb,
        Latitude = gs.Average(x => x.Latitude),
        Longitude = gs.Average(x => x.Longitude),
    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM