[英]How to combine List items
我上了這樣的課:
public class ReportList
{
public int? ProjectId { get; set; }
public string Name { get; set; }
public string ProjectName { get; set; }
public int LevelId { get; set; }
public int Minutes { get; set; }
public int Hours { get; set; }
public int ExtraMinutes { get; set; }
public int ExtraHours { get; set; }
}
我已經列出了這堂課
List<ReportList> repList = new List<ReportList>();
我已將項目添加到此列表中:
repList.Add(new ReportList(1 , "a" , "project a", 2, 30, 1, 45, 2));
repList.Add(new ReportList(1 , "b" , "project a", 2, 30, 2, 15, 1));
repList.Add(new ReportList(1 , "c" , "project a", 2, 0, 3, 10, 0));
我想按總分鍾數和小時數將此列表項合並為一項。 因此,列表應如下所示:
{1, "a", "project a", 2, 60, 6, 70, 3};
我能做什么?
在ProjectId
, ProjectName
和LevelId
字段上使用GroupBy
擴展方法。
var results = repList.GroupBy(x=> new {x.ProjectId, x.ProjectName, LevelId })
.Select(x=> new // or create new ReportList object.
{
ProjectId = x.Key.ProjectId,
ProjectName = x.Key.ProjectName,
Name = x.First().Name, // I assume it is first one as per example, modify if you want.
LevelId = x.Key.LevelId,
Minutes = x.Sum(s=>s.Minutes),
Hours = x.Sum(s=>s.Hours ),
ExtraMinutes = x.Sum(s=>s.ExtraMinutes ),
ExtraHours = x.Sum(s=>s.ExtraHours)
})
.ToList() ;
如果您想要用戶Hari Prasad發布的答案的更優化版本,可以使用以下內容;
int minuteSum = 0;
int hoursSum = 0;
int extraMinutesSum = 0;
int extraHoursSum = 0;
foreach (var report in repList)
{
minuteSum += report.Minutes;
hoursSum += report.Hours;
extraMinutesSum += report.ExtraMinutes;
extraHoursSum += report.ExtraHours;
}
var firstItemInRepList = repList.First();
var result = new ReportList(firstItemInRepList.ProjectId,
firstItemInRepList.Name,
firstItemInRepList.ProjectName,
firstItemInRepList.LevelId,
minuteSum,
hoursSum,
extraMinutesSum,
extraHoursSum);
我知道它的版本更粗略,但占用的CPU更少。
var results = repList
.GroupBy(x => "all")
.Select(x=> new {
ProjectId = x.First().ProjectId,
Name = x.First().Name,
ProjectName = x.First().ProjectName,
LevelId = x.First().LevelId,
Minutes = x.Sum(s=>s.Minutes),
Hours = x.Sum(s=>s.Hours ),
ExtraMinutes = x.Sum(s=>s.ExtraMinutes),
ExtraHours = x.Sum(s=>s.ExtraHours)
});
我指的是用戶Hari Prasad發布的答案,但是根據問題的要求,我們只需要在ProjectId上應用groupby。 請參考下面的代碼。
var processedResult = repList.GroupBy(x => x.ProjectId)
.Select(x => new ReportList
{
ProjectId = x.Key,
ProjectName = x.First().ProjectName, //As per your example it is first row data
Name = x.First().Name, //As per your example it is first row data
LevelId = x.First().LevelId,
Minutes = x.Sum(s => s.Minutes),
Hours = x.Sum(s => s.Hours),
ExtraMinutes = x.Sum(s => s.ExtraMinutes),
ExtraHours = x.Sum(s => s.ExtraHours)
}).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.