Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c#, how to combine strings and their frequency to a resulting string?

Tags:

c#

algorithm

I know that we can find duplicate items like this:

var dublicateItems = itemStrings.GroupBy(x => x)
                                .Where(x => x.Count() > 1)
                                .ToDictionary(g => g.Key, g => g.Count());

And distinct items like this:

var distinctItems = itemStrings.Distinct();

But how to combine it to the following list of string:

input: a, b, b, c, d, d, d, d

output: a, b (2 times), c, d (4 times)

like image 238
Anatoly Avatar asked Jan 17 '26 02:01

Anatoly


1 Answers

You're almost there:

var duplicateItems = 
  itemStrings
  .GroupBy(i => i)
  .Select(i => new { Key = i.Key, Count = i.Count() })
  .Select(i => i.Key + (i.Count > 1 ? " (" + i.Count + " times)" : string.Empty));

If you want the result as a comma-separated string, you can then do this:

var result = string.Join(", ", duplicateItems);
like image 100
Luaan Avatar answered Jan 19 '26 18:01

Luaan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!