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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With