[英]Turning IEnumerable of struct with inner IEnumerable into single dictionary
[英]Turning an IEnumerable of IEnumerables into a dictionary
問題是在跑完之后
reportData = dbContext.FinancialsBySupplierAuditPeriodStatusType
.Where(v => v.ReviewPeriodID == reportFilter.ReviewPeriodID && v.StatusCategoryID == reportFilter.StatusCategoryID)
.GroupBy(s => new { s.SupplierID })
.Select(g => new DrilldownReportItem {
SupplierID = g.Key.SupplierID,
SupplierName = g.Max(v => v.SupplierName),
AccountNo = g.Max(v => v.AccountNo),
TempTotals = g.Select(v => new TempTotals { ClaimType = v.TypeDesc ?? "Old Claims", Amount = v.Amount })
}).OrderBy(r => r.SupplierName).ToList();
Temp totals是一個IEnumerable,它包含一個簡單類的IEnumerable
public class TempTotals {
public string Type { get; set; }
public decimal? Amount { get; set; }
}
我們的想法是獲取這些數據並將其分組到一個字典中,以便我可以獲得所有金額的總和,其中密鑰是類型。
最終結果應如下所示:
Dictionary<string, decimal> test = new Dictionary<string, decimal>() {
{"Claim",2 },
{"Query", 500 },
{"Normal", 700 }
};
我知道我可以預先知道它,但我正在尋找使用LINQ的解決方案。
試試這個:
Dictionary<string, decimal?> test =
reportData
.SelectMany(rd => rd.TempTotals)
.GroupBy(tt => tt.ClaimType, tt => tt.Amount)
.ToDictionary(g => g.Key, g => g.Sum());
由於Amount
的類型是decimal?
那么字典值也是decimal?
。
試試這個:
IEnumerable<IEnumerable<TempTotals>> yourCollection;
var dictionary = yourCollection.SelectMany(s => s).ToDictionary(k => k.Type, v => v.Amount);
dictionary
將是Dictionary<string, decimal>
。 但是你需要確保你不會有兩個具有相同Type
TempTotals
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.