Select EF 6 Net Core 5 中 GroupBy 的 Min()
Select Min() on GroupBy in EF 6 Net Core 5
在按“RateClass”分组的 table 中,我尝试 select“RateClass”、Min(“CostDay”) 和“CostWeek”,但我的代码崩溃了。
var data = db.Rates.GroupBy(t => t.RateClass)
.Select( g => new {
rateClass = g.Select(x => x.RateClass),
costtDay = g.Min(x => x.CostDay),
costWeek = g.Select(x => .CostWeek)
})
.ToList();
正如我在评论中所述,它不会编译,因为你在这里缺少 x costWeek = g.Select(x => .CostWeek)
,应该是 costWeek = g.Select(x => x.CostWeek)
此外,您是否尝试为每个组创建一个条目?如果是这样,你可以试试这个...
public class Rates
{
public string RateClass { get; set; }
public decimal CostDay { get; set; }
public decimal CostWeek { get; set; }
}
var rates = new List<Rates>
{
new Rates {CostDay = 2, CostWeek = 7, RateClass = "Test 1"},
new Rates {CostDay = 4, CostWeek = 17, RateClass = "Test 1"},
new Rates {CostDay = 6, CostWeek = 27, RateClass = "Test 2"},
new Rates {CostDay = 8, CostWeek = 37, RateClass = "Test 2"}
};
var data = rates.GroupBy(t => t.RateClass)
.Select(g => new Rates {
RateClass = g.Key,
CostDay = g.Min(x => x.CostDay),
CostWeek = g.Sum(x => x.CostWeek)
})
.ToList();
RateClass 将是您分组的关键,我只是以 CostWeek 为例进行总结。这里有一个 link 可以试试。
在按“RateClass”分组的 table 中,我尝试 select“RateClass”、Min(“CostDay”) 和“CostWeek”,但我的代码崩溃了。
var data = db.Rates.GroupBy(t => t.RateClass)
.Select( g => new {
rateClass = g.Select(x => x.RateClass),
costtDay = g.Min(x => x.CostDay),
costWeek = g.Select(x => .CostWeek)
})
.ToList();
正如我在评论中所述,它不会编译,因为你在这里缺少 x costWeek = g.Select(x => .CostWeek)
,应该是 costWeek = g.Select(x => x.CostWeek)
此外,您是否尝试为每个组创建一个条目?如果是这样,你可以试试这个...
public class Rates
{
public string RateClass { get; set; }
public decimal CostDay { get; set; }
public decimal CostWeek { get; set; }
}
var rates = new List<Rates>
{
new Rates {CostDay = 2, CostWeek = 7, RateClass = "Test 1"},
new Rates {CostDay = 4, CostWeek = 17, RateClass = "Test 1"},
new Rates {CostDay = 6, CostWeek = 27, RateClass = "Test 2"},
new Rates {CostDay = 8, CostWeek = 37, RateClass = "Test 2"}
};
var data = rates.GroupBy(t => t.RateClass)
.Select(g => new Rates {
RateClass = g.Key,
CostDay = g.Min(x => x.CostDay),
CostWeek = g.Sum(x => x.CostWeek)
})
.ToList();
RateClass 将是您分组的关键,我只是以 CostWeek 为例进行总结。这里有一个 link 可以试试。