我有表 ReportData 有以下記錄
| 機構 | 年 | 月 | 月數 |
|---|---|---|---|
| 一 | 2017年 | 簡 | 4 |
| 一 | 2017年 | 二月 | 6 |
| 一 | 2017年 | 十一月 | 29 |
| 一 | 2017年 | 十二月 | 38 |
| 一 | 2018年 | 簡 | 20 |
| 一 | 2019年 | 二月 | 18 |
| 二 | 2017年 | 簡 | 24 |
| 二 | 2017年 | 二月 | 66 |
| 三 | 2017年 | 十一月 | 9 |
| 四 | 2017年 | 十二月 | 8 |
| 四 | 2018年 | 簡 | 22 |
| 四 | 2019年 | 二月 | 48 |
如何轉換成下表?請讓我知道 Linq 宣告。提前謝謝你的幫助。
| 機構 | 月 | 2017年 | 2018年 | 2019年 |
|---|---|---|---|---|
| 一 | 簡 | 4 | 20 | 0 |
| 一 | 二月 | 6 | 0 | 18 |
| 一 | 十一月 | 29 | 0 | 0 |
| 一 | 十二月 | 38 | 0 | 0 |
| 二 | 簡 | 24 | 0 | 0 |
| 二 | 二月 | 66 | 0 | 0 |
| 三 | 十一月 | 9 | 0 | 0 |
| 四 | 簡 | 0 | 22 | 0 |
| 四 | 二月 | 0 | 0 | 48 |
| 四 | 十二月 | 8 | 0 | 0 |
源類結構
public class ReportingData
{
public string AgencyName { get; set; }
public int Year { get; set; }
public string MonthNumnber { get; set; }
public string Month { get; set; }
public int MonthCount { get; set; }
}
uj5u.com熱心網友回復:
在我看來,每個 [Agency, Month] 組合,您都需要 2017..2019 年的 MonthCounts。
我想知道你幾年后想要什么:只有最近三年?還是 2017 年……2025 年?但那是后來的問題。
我的建議是使 ReportData 組具有相同的 [Agency, Month] 組合值。使用具有引數 resultSelector 的 Enumerable.GroupBy的 多載 來精確定義結果。如果您的資料位于不同的行程(通常是資料庫)中,請使用 IQueryable 版本。
IEnumerable<Report> reportData = ...
// make groups with same values for [Agency, Month] combination
var result = reportData.GroupBy(report => new
{
Agency = report.Agency,
Month = report.Month,
},
// parameter resultSelector: for every [Agency, Month] combination,
// and all reports that have this [Agency, Month] combination,
// make one new:
(agencyMonthCombination, reports] => new
{
Agency = agencyMonthCombination.Agency,
Month = agencyMonthCombination.Month,
Year2017 = reports.Where(report => report.Year == 2017)
.Select(report => report.MonthCount)
.Sum();
Year2018 = reports.Where(report => report.Year == 2018)
.Select(report => report.MonthCount)
.Sum();
Year2019 = reports.Where(report => report.Year == 2018)
.Select(report => report.MonthCount)
.Sum();
如果您希望每年只有一份報告,則不必求和,只需使用 FirstOrDefault。
您會看到這種將年份命名為 2017..2019 的方法的缺點。如果您在所有年份或最近 N 年都撰寫代碼,則代碼會容易得多:
// parameter resultSelector
(agencyMonthCombination, reports] => new
{
Agency = agencyMonthCombination.Agency,
Month = agencyMonthCombination.Month,
// group the reports with this [Agency, Month] combination in years
MonthCounts = reports.GroupBy(report => report.Year,
(year, reportsInThisYear) => new
{
Year = year,
MonthCount = reportsInThisYear.Select(report => report.MonthCount).Sum(),
})
// if you only want the last N: orderby descending Year and Take(N)
.OrderByDescending(yearMonthCount => yearMonthCount.Year)
.Take(N)
.ToList(),
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397987.html
標籤:。网 asp.net-mvc 林克
