How can I group in Linq?

Tag class

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

      

and my request

 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 above approach is that I cannot render as TagId

well TagLink

. How can I fix this?

+3


source to share


1 answer


Assuming Tag

you get unique TagId

and for each 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 can 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);

      

+5


source







All Articles