记录集

时间:2015-11-23 20:42:51

标签: c# linq

我被困在如何在查询中总计一笔钱。这是代码:

public ActionResult GetCommissionSummary(string agencyId, string month, string year)
{
     try
     {
         var as400rep = new iSeriesRepository(new iSeriesContext());
         var results = as400rep.GetCommissionSummary(agencyId, month, year).ToList();
         var CollectionSummary = Mapper.Map<IEnumerable<CommissionSummary>, IEnumerable<CommissionSummaryViewModel>>(results);
         var vm = new CommissionSummaryViewModel
         {
             Month = month,
             Year = year,
             CommissionSummary = CollectionSummary,
             CommissionsGrandTotal = results.Sum(x => decimal.Parse(x.CommissionAmount))
         };
         return PartialView("~/Areas/Insurance/Views/AgencyManagement/_CommissionSummary.cshtml", vm);
     }
     catch (Exception ex)
     {
         Log.Error(ex.Message, ex.InnerException);
            throw;
     }
}

我想出了如何获得总计,非常简单,但现在我还需要通过政策获得一笔金额(这是结果中返回的字段之一。无法找到一个示例&& #39;很简单,可以遵循。

1 个答案:

答案 0 :(得分:1)

我希望以下示例有所帮助。它显示了使用GroupBy以及按组创建小计。

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        enum Policy
        {
            A, B, C
        }

        struct Row
        {
            public Policy p;
            public int commission;
        }

        static void Main(string[] args)
        {
            const int MAX = 100;

            List<Row> rows = new List<Row>(MAX);
            Random rand = new Random(0);
            for (int x=0; x < MAX; x++)
            {
                int policy = rand.Next(3);
                int comm = rand.Next(1000);

                rows.Add(new Row() { p = (Policy)policy, commission = comm });
            }

            var query = rows.GroupBy(row => row.p, (policy, r) => new { Policy = policy, Sum = r.Sum(t => t.commission) });

            foreach(var result in query)
            {
                Console.WriteLine(result.Policy + ": " + result.Sum);
            }
            Console.ReadLine();
        }
    }
}