0

有人对我如何仅使用 LINQ 执行此操作有任何建议吗?

var statements = db.vwOutstandingStatements.ToList();

var amounts = (from s in db.vwOutstandingStatements
                  group s by s.Id into v
                  select new 
                  {
                      Id = v.Key,
                      amount = v.Sum(a => a.Amount)
                  }).ToList();

List<vmVendorStatements> statementsToProcess = new List<vmVendorStatements>();

foreach (var amount in amounts)
{
    var statement = statements.Find(s => s.Id == amount.Id);
    statementsToProcess.Add(new vmVendorStatements()
    {
        Id = statement.Id,
        PropertyAddress = statement.PropertyNumber + " " + statement.PropertyStreet + " " + statement.PropertyTown,
        StatementDate = statement.StatementDate.ToLongDateString(),
        Amount = amount.amount.ToString()
    });
}

语句来自通过 EF5 的 sql 视图。我运行 LINQ 以获取按返回视图中的金额总和分组的数据,然后将其连接回来以显示返回视图中的一些详细信息以及总和金额。StatementsToView 是我将数据放入 MVC 视图的视图模型。

我确信它可以在 SQL 中完成,并且无论如何我都可以这样做,但似乎也必须有一个更简洁的解决方案来解决上述问题。

谢谢,

杰森。

4

1 回答 1

3

您可以只提取组中的第一项,而不是重新查询以找到第一项:

var statementsToProcess =
    (from s in db.vwOutstandingStatements
    group s by s.Id into v
    let first = v.First()
    select new vmVendorStatements()
    {
        Id = v.Key,
        amount = v.Sum(a => a.Amount),
        PropertyAddress = first.PropertyNumber + " " + first.PropertyStreet + " " + first.PropertyTown,
        StatementDate = first.StatementDate.ToLongDateString(),
    }).ToList();
于 2013-09-23T15:50:39.390 回答