OrElse
OrElse

Reputation: 9959

How can i group by in Linq?

The Tags class is

public class Tags
    {
        public int TagId;
        public string Tag;
        public string TagLink;
        public int TagCount;
    }

and my query is

 var v = db.QuestionTags
           .GroupBy(n => n.Tag.Tag1)
           .Select(n => new Tags
           {
               Tag = n.Key,
               TagCount = n.Count()
           }
           )
           .OrderByDescending(n => n.TagCount);

The problem with the approach above is that i cannot map also the TagId and the TagLink. How can i fix that?

Upvotes: 3

Views: 39

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Assuming that for each Tag you get a unique TagId and TagLink, you can use First() to set them:

var v = db.QuestionTags
    .GroupBy(n => n.Tag.Tag1)
    .Select(n => new Tags {
        Tag = n.Key,
        TagCount = n.Count(),
        TagId = n.First().TagId,
        TagLink = n.First().TagLink
    })
    .OrderByDescending(n => n.TagCount);

If these properties may be different for the same Tag, group by their combination:

var v = db.QuestionTags
    .GroupBy(n => new {n.Tag.Tag1, n.TagId, n.TagLink})
    .Select(n => new Tags {
        Tag = n.Key.Tag1,
        TagCount = n.Count(),
        TagId = n.Key.TagId,
        TagLink = n.Key.TagLink
    })
    .OrderByDescending(n => n.TagCount);

Upvotes: 5

Related Questions