更好的总结方式

时间:2013-07-21 13:16:56

标签: c# linq

我遇到了以模块化方式汇总项目的问题。

我有这堂课:

public enum ReportType
{
  Worker,
  Management,
  Guest
}

public class Report
{
  public ReportType Type { get; set; }
  public int Lost { get; set; }

  public Report(ReportType typ, int los)
  {
     Type = typ;
     Lost = los;
  }
}

以及获取Report列表的方法,并且应找出并返回损失最大的Report列表,并根据该数字进行一些计算。 我开始了这个方法:

public class ReportsManager
{
  public static List<Report> CalculateBiggerLost(List<Report> reportList)
  {
     int WorkerSum = 0;
     int ManagementSum = 0;
     int GuestSum = 0;

     foreach (Report report in reportList)
     {
        switch (report.Type)
        {
              case ReportType.Guest:
              {
                 GuestSum += report.Lost;
                 break;
              }
              case ReportType.Management:
              {
                 ManagementSum += report.Lost;
                 break;
              }
              case ReportType.Worker:
              {
                 WorkerSum += report.Lost;
                 break;
              }
        }
     }

     if (GuestSum >= ManagementSum && GuestSum >= WorkerSum)
     {
        // Doing some report
     }
     else if (WorkerSum >= ManagementSum)
     {
        // inner Check
     }
  }
}

但是如果我在ReportType枚举中可能有另一个值,那就不好了,然后必须重写代码,再加上它不那么可读。我是linq的新手,但是我开始尝试GroupBy使用linq,但是当我得到并回答reportList.GroupBy(x => x.Type);并且不知道如何处理它时会陷入困境,因为结构是什么?我该怎么迭代呢?

2 个答案:

答案 0 :(得分:11)

这是您想要的查询:

var results = reportList.GroupBy(r => r.Type)
                        .ToDictionary(g => g.Key, g => g.Sum(r => r.Lost));
int WorkerSum = results[ReportType.Worker];
int ManagementSum = results[ReportType.Management];
int GuestSum = results[ReportType.Guest];

如果您希望每种类型至少有一个报告,这将正常工作。如果可能没有给出类型的报告,则必须首先检查,如下所示:

int WorkerSum = results.ContainsKey(ReportType.Worker) ? results[ReportType.Worker] : 0;
int ManagementSum = results.ContainsKey(ReportType.Management) ? results[ReportType.Management] : 0;
int GuestSum = results.ContainsKey(ReportType.Guest) ? results[ReportType.Guest] : 0;

或者像这样:

int WorkerSum;
int ManagementSum;
int GuestSum;
results.TryGetValue(ReportType.Worker, out WorkerSum);
results.TryGetValue(ReportType.Management, out ManagementSum);
results.TryGetValue(ReportType.Guest, out GuestSum);

答案 1 :(得分:3)

int guestSum = reportList.Where(x=>x.Type==ReportType.Guest).Sum(x=>x.Lost);
int workerSum = reportList.Where(x=>x.Type==ReportType.Worker).Sum(x=>x.Lost);
int managementSum = reportList.Where(x=>x.Type==ReportType.Manment).Sum(x=>x.Lost);