开发者

How to combine rows using LINQ?

Say I have an entity with following properties [Id, UserName, ProductName], where Id is the PK, and other fields are not unique, so the rows with same UserName repeat multiple times.

For one of the views I need to get a collection that would have unique UserName, and other fields would be combined together using string concatenation or something similar.

If I have

[0, John, Alpha]
[1, Mary, Beta]
[2, John, Gam开发者_JAVA百科ma]

I need a query that would get me a collection like

[John, Alpha Gamma]
[Mary, Beta]

And it would be awesome if all that could be accomplished on the database side without loading the entities.


You are looking for GroupBy():

var results = context.MyEntities.GroupBy( x => x.UserName);

foreach (var item in results)
{
    Console.WriteLine("{0} : {1}", item.Key, string.Join(",", item.Select( x=> x.ProductName));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜