我在串列中有以下物件(toInsertDatesRecords)。
class SafeProtectDeviceReportUsage
{
public long Vehicleid { get; set; }
public DateTime TimestampLastConnection { get; set; }
// Minutes
public double AvgConnectionDuration { get; set; }
}
我需要回傳特定日期 (dd/MM) 所有車輛的平均 AvgConnectionDuration。
這是一個資料樣本,同一車輛的 AvgConnectedDuration 的許多值。
| 日期 | 車輛編號 | AvgConnectedDuration |
|---|---|---|
| 05/02 | 1 | 302 |
| 05/02 | 1 | 1129 |
| 05/02 | 5 | 500 |
| 05/03 | 1 | 1440 |
預期的結果是
| 日期 | 數數 | 期間 |
|---|---|---|
| 05/02 | 2 | 302 1129 500 / 2 |
| 05/03 | 1 | 1440 / 1 |
我提出了以下查詢:
var toBeReturned = toInsertDatesRecords.GroupBy(row => row.TimestampLastConnection.ToLocalTime().Date)
.Select(g =>
{
int vCount = g.Select(c => c.Vehicleid).Distinct().Count();
return new
{
date = g.Key.Date,
count = vCount,
duration = g.Average(c => c.AvgConnectionDuration)
};
});
這是錯誤的,因為在計算所有車輛的平均持續時間之前,我需要先對每輛車在特定日期的 AvgConnectionDuration 求和。
我不知道如何分組兩次。
uj5u.com熱心網友回復:
從您的樣本資料和預期結果中,您可以嘗試使用Sum和劃分您的計數,而不是使用Average
var result = toInsertDatesRecords
.GroupBy(row =>row.TimestampLastConnection.ToLocalTime().Date)
.Select(g =>
{
int vCount = g.Select(c => c.Vehicleid).Distinct().Count();
return new
{
date = g.Key.Date,
count = vCount,
AvgConnectedDuration = g.Sum(x=> x.AvgConnectionDuration) / vCount
};
});
我認為我們可以使用g.GroupBy(x=>x.Vehicleid).Count()count 來簡化。
var result = toInsertDatesRecords
.GroupBy(row =>row.TimestampLastConnection.ToLocalTime().Date)
.Select(g =>
{
int vCount = g.GroupBy(x=>x.Vehicleid).Count();
return new
{
date = g.Key.Date,
count = vCount,
AvgConnectedDuration = g.Sum(x=> x.AvgConnectionDuration) / vCount
};
});
c# 在線
uj5u.com熱心網友回復:
嘗試以下:
var toBeReturned = toInsertDatesRecords.GroupBy(row => row.TimestampLastConnection.ToLocalTime().Date)
.Select(g => new {
date = g.Key.Date,
count = g.Select(c => c.Vehicleid).Distinct().Count(),
duration = g.Average(c => c.AvgConnectionDuration)
}
).select(g => new {date = g.date, count = g.Sum(h => h.count), duration = g,Average(h => h.count));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471244.html
