我想從“ 1)LabelName, 2)OpenLabelStandard, 3)Type 列中洗掉重復的值。問題是我的表有四列。除了前三列之外,我還有另一列稱為 4)'距離'。它不是資料庫中的欄位。我使用視圖模型中的一些計算將它添加到我的表中。每行的距離列都是可變的,所以當我使用 Distinct() 時,由于距離列,它不起作用。
例如,目前我喜歡下面的這張表。
LabelName OpenLabelStandard Type Distance
A1 A2 A3 30
A1 A2 A3 50
A1 A2 A3 100
B1 B2 B3 15
B1 B2 B3 60
我需要結果如下
LabelName OpenLabelStandard Type Distance
A1 A2 A3 30
B1 B2 B3 15
這是我在控制器中的選擇。
var listdata = (from c in _context.OpenLabelTag select c )
.Select(x=> new {x.LabelName,x.OpenLabelStandard,x.Type, Distance = x.Coordinates.Distance(searchArea),x.Coordinates})
.OrderBy(s=>s.Coordinates.Distance(searchArea))
.Where(x=>x.Coordinates.IsWithinDistance(searchArea,InputRadius) && x.OpenLabelStandard !=null)
.Take(10).ToList().Distinct()
;
你有什么線索我該如何解決?
uj5u.com熱心網友回復:
您不能對屬性的子集應用 distinct 并仍然保留其余屬性,因為不同的“組”值。未包含在不同結果中的其他屬性不能成為結果的一部分,因為它們可能具有多個不同的值(例如您的距離示例)。
正如 HoneyBadger 所建議的,您可以使用 a 模擬 distinct GroupBy(),然后選擇所有.Key屬性并計算其余屬性的聚合函式:
var listdata = (from c in _context.OpenLabelTag select c)
.Select(x => new { x.LabelName, x.OpenLabelStandard, x.Type, Distance = x.Coordinates.Distance(searchArea), x.Coordinates })
.Where(x => x.Coordinates.IsWithinDistance(searchArea, InputRadius) && x.OpenLabelStandard != null)
.GroupBy(x => new { x.LabelName, x.OpenLabelStandard, x.Type })
.Select(gr => new
{
gr.Key.LabelName,
gr.Key.OpenLabelStandard,
gr.Key.Type,
MinDistance = gr.Min(x => x.Distance)
})
.OrderBy(s => s.MinDistance)
.Take(10).ToList();
請注意,在分組操作之后,我洗掉了Distinct()并且還移動了to 。OrderBy()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/414237.html
標籤:
