Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a string
C#
string chars = "A|A|B|A+|C|B+|A+|C|A|B+|B";


from above string I would like to remove duplicate items and count occurrence of each unique item.

Result should be like >> A: 3; A+: 2; B: 2; B+: 2; C: 2

I would like to achieve above in C#.

Thanks in advance.
Posted

Try this:
C#
string chars = "A|A|B|A+|C|B+|A+|C|A|B+|B";
string output = string.Join("; ", chars.Split('|')
    .GroupBy(x => x)
    .OrderBy(x => x.Key)
    .Select(x => string.Format("{0}: {1}", x.Key, x.Count())));
Console.WriteLine(output);

Output: A: 3; A+: 2; B: 2; B+: 2; C: 2
 
Share this answer
 
Comments
sam7one 17-Nov-13 9:39am    
Thanks for prompt reply, both the answers serve my purpose...
Thomas Daniels 17-Nov-13 9:39am    
You're welcome!
OriginalGriff 17-Nov-13 9:54am    
Hah! Snap! :laugh:
Linq methods make it pretty simple:
C#
string chars = "A|A|B|A+|C|B+|A+|C|A|B+|B";
string[] sep = chars.Split('|');
List<string> withCount = sep.GroupBy(s => s).Select(g => g.Key+ " : " + g.Count()).ToList();
foreach (string s in withCount)
    {
    Console.WriteLine(s);
    }
 
Share this answer
 
Comments
sam7one 17-Nov-13 9:39am    
Thanks for prompt reply, both the answers serve my purpose...
OriginalGriff 17-Nov-13 9:54am    
You're welcome!
Thomas Daniels 17-Nov-13 10:25am    
I voted 4, because, first of all, you used string concatenation, and it's better to use string.Format, and second, because it is not necessary to convert the results to a list. Foreach also works on an IEnumerable<T>

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900