我正在嘗試創建一個基本上會像這樣分解的樹視圖:
- Year
- Month
- Related Item
所以我們可能有 2022 年,它在幾個月內有幾個相關專案。
我創建了以下模型:
public class TreeYear
{
public string NodeYear { get; set; }
public DateTime CreatedDateTime { get; set; }
public List<TreeMonth> Months { get; set; }
}
public class TreeMonth
{
public int MonthID { get; set; }
public string MonthName { get; set; }
public quoteSummary QuoteSummary{ get; set; }
}
我在我的控制器中撰寫了一些代碼,當前回傳每個專案,如下所示:
var allQuotes = QuoteSummary.ToList();
var tree = new TreeYear();
foreach (var quote in allQuotes)
{
tree.NodeYear= quote.CreatedTime.Year.ToString();
tree.CreatedDateTime = quote.CreatedTime;
tree.Months = new List<TreeMonth>()
{
new TreeMonth() {
MonthID = quote.CreatedTime.Month,
MonthName = getAbbreviatedName(quote.CreatedTime.Month),
QuoteSummary = quote
}
};
}

但顯然在這里你可以看到它有所有 41 條記錄,其中沒有按年份分組。
我想也許我可以寫一些類似但目前不正確的 linq:
var groups = TheResponse.Details
.GroupBy(
d => Int32.Parse(d.NodeYear),
(key, g) => g.GroupBy(
d => d.Months.Select(x => x.MonthID)),
(key2, g2) => g2.GroupBy(d => d.CreatedDateTime)
)
);
還是我需要更改模型才能使這個想法起作用?
uj5u.com熱心網友回復:
如果我正確理解了您的問題,那么您需要展平內部串列,然后再次按月分組。
var groups = TheResponse.Details
.GroupBy(d => Int32.Parse(d.NodeYear))
.Select(d => new
{
Year = d.Key,
MonthObj = d.SelectMany(m => m.Months)
.GroupBy(m => m.MonthID)
.Select(x => new
{
MonthID = x.Key,
RelatedItem = x.ToList()
})
});
我已經通過使用匿名型別對其進行了簡化,但是您顯然可以根據您的回應對其進行調整。Model.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/498020.html
上一篇:如何使用Expression.Lambda選擇多個列?
下一篇:比較串列時xUnit測驗失敗
