开发者

how to do grouping in LINQ

I'm trying to do a LINQ query to a list of RelatedProducts objects. I have to group them by CategoryId so I'm using the group by clause. Unfortunatly I just realized I can't simply use 'select g.Value' at the end. The group is a IGrouping and I want to return just the RelatedProduct here. How can I do this?

Also in my case a product can be in 2 categories at once, so how can I prevent LINQ from returning duplicates? I'm only interested in the first category (actualy it doesn't matter as long it's assigned to that product).

var query = from rp in context.RelatedProducts
                    join p in context.Products on rp.ProductId2 equals p.ProductId
                    join pc in context.ProductCategories on p.ProductId equals pc.ProductId
                    where rp.ProductId1 == productId1 &&
                    !p.Deleted &&
                    (showHidden || p.Published)
                    orderby rp.DisplayOrder
   开发者_如何学C                 group rp by pc.CategoryId into g
                    select g;


In your case g is IEnumerable so you can just use select g.First() or apply any kind of additional filtering to it.


I managed to do it like this:

List<RelatedProduct> relatedProducts = new List<RelatedProduct>();
        foreach (var group in query)
        {
            var key = group.Key;
            relatedProducts.AddRange(group.ToList());
        }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜