how to do grouping in LINQ  

  RSS

pankaj Gupta
(@pankaj-gupta)
Active Member Moderator
Joined: 1 year ago
Posts: 6
18/05/2018 4:49 pm  

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
                    group rp by pc.CategoryId into g
                    select g;

ReplyQuote
TechGroup Admin
(@admin)
Eminent Member Admin
Joined: 1 year ago
Posts: 11
18/05/2018 4:51 pm  

I managed to do it like this check this:

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

ReplyQuote
Share:
  
Working

Please Login or Register