问题描述
如何使用Linq对列表进行分组?我使用以下linq表达式从数据库中获取数据,如何修改我的代码以按PartyName字段对结果进行分组?
How can i use Linq and group a list? I have the following linq expression to get data from the database, how can i modify my code to group results by PartyName Field?
var RParty = await context.Parties
.Where(b => b.ID == request.ID)
.ToListAsync();
我尝试了
var RParty = await context.Parties
.Where(b => b.ID == request.ID)
.GroupBy(b => b.PartyName)
.ToListAsync();
但是我收到此错误
System.InvalidOperationException: Client side GroupBy is not supported.
推荐答案
要在mjwills发布的github链接上进行扩展,这里的问题是您可能要执行两种不同的GroupBy,即SQL Group By或C#LINQ分组依据.
To expand on the github link posted by mjwills, the issues here is there are two different GroupBys you could be executing, a SQL Group By, or a C# LINQ Group By.
这里的一种解决方案是切换呼叫顺序:
One solution here is to switch the order of your calls:
var RParty = await context.Parties
.Where(b => b.ID == request.ID)
.ToListAsync()
.GroupBy(b => b.PartyName); // <-- move after ToList
通过调用ToList,数据将被视为C#类型,并且LINQ GroupBy函数应该起作用.
By calling ToList the data will be treated as a C# type and the LINQ GroupBy function should work.
但是,您需要小心,因为一旦调用ToList,数据就会从数据库返回并存储在服务器的内存中.取决于缔约方"表的大小,可能会导致性能问题
However, you need to be careful because once you call ToList the data will be returned from the database and be stored in memory on the server. Depending on how large the Parties table is expected to be it could cause performance issues
这篇关于在Linq中使用GroupBy:不支持客户端GroupBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!