fireaxe
fireaxe

Reputation: 1

Count duplicates and combine them in a list

I have a list like this:

var list = new List<string>() { "a", "b", "c", "a" };

As you can see I have one duplicate inside this list.

The desired output should look like this:

a (2)
b (1)
c (1)

The code which I already have looks like this:

list.GroupBy(x => x).Select(x => x.Key + "(" + x.Count() + ")").ToList().ForEach(x => list2.Add(x));

But as you can see I need a second list to get the desired output. My question now is how can I get the desired output with using only one list.

Upvotes: 0

Views: 1060

Answers (4)

Don CorliJoni
Don CorliJoni

Reputation: 248

You can use the Distinct method to remove duplicates. This returns a IEnumerable and in order to use the ForEach method you have to apply the ToList method first. The Foreach iterates over the items {"a", "b", "c"} and prints the current item and the count of this item in the list with dulicates.

list.Distinct().ToList().ForEach(v1 => Console.WriteLine($"{v1} ({list.Count(v2 => v1 == v2)})"))

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109547

You can do this in one statement (I've split it over multiple lines for readability):

var list = new List<string> { "a", "b", "c", "a" };

Console.WriteLine(
    string.Join("\n", 
        list.GroupBy(_=>_).Select(g => $"{g.Key} ({g.Count()})")));

Output:

a (2)
b (1)
c (1)

Upvotes: 0

JuanR
JuanR

Reputation: 7783

This does what you need:

var list = new List<string>() { "a", "b", "c", "a" };
foreach (var group in list.GroupBy(b => b).OrderBy(g => g.Key))
{
    Console.WriteLine($"{group.Key} ({group.Count()})");
}

Consequentially, if one wishes to dedup this list, one could do:

list = list.GroupBy(b => b).Select(g => g.Key).ToList();

The result would be a deduped list with "a", "b" and "c" in it.

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Why don't we just add the items into existing list2?

var list2 = new List<string>();

...

list2.AddRange(list
  .GroupBy(item => item)
  .Select(group => $"{group.Key} ({group.Count()})"));

Or create list2 from scratch:

var list2 = list
  .GroupBy(item => item)
  .Select(group => $"{group.Key} ({group.Count()})")
  .ToList();

Upvotes: 1

Related Questions