记录集中的LINQ查询和
本文关键字:查询 LINQ 集中 记录 | 更新日期: 2023-09-27 18:23:56
我一直纠结于如何在查询中求和。这是代码:
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;
}
}
我想好了如何获得总数,非常简单,但现在我还需要按策略获得总和(这是结果中返回的字段之一。找不到足够简单的示例。
我希望下面的例子能有所帮助。它显示了使用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();
}
}
}