简体   繁体   中英

linq to entities group by sub-query

I have the following code:

var statements = db.statement
                .OrderByDescending(d => d.id)
                .Take(5)
                .AsEnumerable()
            .Select(d => new Statements
                             {
                                 Accounts = d.statement_entry.AsEnumerable()
                                     .GroupBy(b => b.currency)
                                     .Select(b =>
                                             new Account
                                                 {
                                                     In = b.Where(l => l.amount > 0).Sum(l => l.amount),
                                                     Out = b.Where(l => l.amount < 0).Sum(l => l.amount),
                                                     Balance = b.Sum(l => l.amount),
                                                     Currency = b.Key
                                                 }).OrderBy(b => b.Currency),
                                 UploadedDate = d.uploaded_date,
                                 Id = d.id
                             })
                .ToList();

Is there a way that I could do it without the AsEnumerable() ? From what I understand the AsEnumberable will cause a query to take place for each of the statement s returned.

Or is there a better way to refactor the code?

You understand wrongly. AsEnumerable will make the query execute on the local (client) machine.

This

statements = db.statement
            .OrderByDescending(d => d.id)
            .Take(5)

will be executed on the (SQL) server,

the remaining part on the client

Why are you puttin the AsEnumerable ? I think the query should work even without (and it would do everything server-side)

The only thing is that after the OrderBy(b => b.Currency) you should put a .ToList() so that the .Select(b => new Account is materialized and cached.

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