简体   繁体   中英

Perform group and join using LINQ

Does anyone have any suggestions about how I might do this using just 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()
    });
}

Statements is from a sql view via EF5. I run the LINQ to get the data grouped by the sum of the amounts in the returned view and then join it back to show some of the detail from the returned view along with the sums amounts. StatementsToView is my view model to get the data into an MVC view.

I'm sure it could be done in SQL, and I might do that in any case, but there also seems as though there must be a neater solution to the above too.

Thanks,

Jason.

You can just grab out the first item in the group rather than re-querying just to find the first item:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM