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.
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; }
}
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();
精彩评论