views:

65

answers:

2

I have a tag list which contains a list of duplicated tags, such as "tag1", "tag1", "tag2", "tag3", "tag3" and "tag2".

I want to calculate and how many tag1, tag2 and tag3 are in the list, and then add them into a new tag list such as var tagList = new List<Tag>(), it will have thousands of the tags in the list. Can anyone one help me to achieve this in an effective way? The list should have the tag name and the number of tags (count).

Here is the my Tag class properties:

    public int TagID { get; set; }
    public string TagName { get; set; }
    public int TagCount { get; set; }

Many thanks.

+2  A: 

I can't tell from your description if you have an IEnumerable<string> representing the tags or an IEnumerable<Tag> representing the tags so here is an approach for both:

For the Tag case:

List<Tag> tags = new List<Tag>() {
    new Tag() { TagName = "tag1" },
    new Tag() { TagName = "tag1" },
    new Tag() { TagName = "tag2" },
    new Tag() { TagName = "tag3" },
    new Tag() { TagName = "tag3" },
    new Tag() { TagName = "tag2" }
};
var tagList = tags.GroupBy(t => t.TagName)
                  .Select(g => new Tag() {
                      TagName = g.Key,
                      TagCount = g.Count()
                  })
                  .ToList();

For the string case:

List<string> list = new List<string>() {
    "tag1",
    "tag1",
    "tag2",
    "tag3",
    "tag3",
    "tag2"
};
var tagList = list.GroupBy(s => s)
                  .Select(g => new Tag() {
                      TagName = g.Key,
                      TagCount = g.Count() 
                  })
                  .ToList(); 

In both cases I used the definition

class Tag {
    public int TagID { get; set; }
    public string TagName { get; set; }
    public int TagCount { get; set; }
}
Jason
Hi Jason, thank you! But tag list is the List<Tag> not the List<string>. :)
Daoming Yang
@DotNet User: Addressed.
Jason
Thank you very much Jason. I understand this now. Is there any thing I could to ignore case during the group by?
Daoming Yang
Sure, you could replace `t => t.TagName` in the above by `t => t.TagName.ToLower()`.
Jason
Thank you Jason. It works great for me. I was wandering how this can be done in the old days without Linq.
Daoming Yang
You're dropping the TagID. I hope it's not important.
tvanfosson
A: 

If I understand your question properly, I think this will work. You want to group by the tag id and name, then sum the count for each of the tags in the existing list.

var tagList = existingList.GroupBy( t => new { t.TagID, t.TagName } )
                          .Select( g => new Tag {
                                         TagID = g.Key.TagID,
                                         TagName = g.Key.TagName,
                                         TagCount = g.Sum( t => t.TagCount )
                          })
                          .ToList();
tvanfosson
Thank you @tvanfosson.
Daoming Yang