[英]LINQ group-by and then display datetime for (dd mmm)
我希望Linq按日期分組但以文本顯示
這是我的代碼
var groups = _uow.Orders.GetAll()
.Where(x => x.Created > baselineDate)
.GroupBy(x => x.Created.ToString("yyyy-MM-dd"));
var orders = new
{
Day = groups.Select(g => g.Key).ToArray(),
Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(),
};
結果是(不好放在圖形標簽中)
{"Day": [2, 3, 4, 5], "Total": [9999.00, 9999.00, 9999.00, 9999.00] }
但是我想要這個(每月)
"Day": ['Jan', Feb', 'Mar', 'Apr'], "Total": [9999.00, 9999.00, 9999.00, 9999.00] }
或每日
"Day": ['Jan 1', 'Jan 2', 'Jan 3', 'Jan 4'], "Total": [9999.00, 9999.00, 9999.00, 9999.00] }
請給我建議我可以玩的DateTime.ToString()。
謝謝你們。
謝謝大家的幫助。 我找到了答案。
加
.AsEnumerable()
和
.GroupBy(x => x.Created.ToString("MMM d"));
這是完整的代碼
var groups = _uow.Orders.GetAll()
.Where(x => x.Created > baselineDate)
.AsEnumerable()
.GroupBy(x => x.Created.ToString("MMM d"));
var orders = new
{
Day = groups.Select(g => g.Key).ToArray(),
Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(),
};
此問題描述如何將日期時間轉換為月份的字符串名稱。
編輯:對於EF,我們必須先將所有內容拉入內存,然后再執行任何字符串邏輯:
var orders = _uow.Orders.GetAll()
.Where(x => x.Created > baselineDate)
// pull into memory here, since we won't be making the result set any smaller and
// we want to use DateTime.ToString(), which EF won't compile to SQL
.AsEnumerable()
// this will group by the whole date. If you only want to group by part of the date,
// (e. g. day or day, month), you could group by x => x.Date.Month or the like
.GroupBy(x => x.Date)
.Select(g => new {
// or use just "MMM" for just the month
Dates = g.Select(g => g.Key.ToString("MMM d")).ToArray(),
Total = ...
});
您需要使用EF可以理解並轉換為SQL的函數,例如EntityFunctions.TruncateTime
。 這是您更新的代碼:
var groups = _uow.Orders.GetAll()
.Where(x => x.Created > baselineDate)
.GroupBy(x => EntityFunctions.TruncateTime(x.Created));
然后,僅在輸出中使用字符串格式,但是請確保在將值返回到.Net之后使用AsEnumerable
切換到Linq-to-Objects進行格式化:
var orders = new
{
Day = groups.Select(g => g.Key)
.AsEnumerable()
.Select(x => x.ToString("MMM d"))
.ToArray(),
Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(),
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.