Home > front end >  Count duplicates and combine them in a list
Count duplicates and combine them in a list

Time:03-17

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.

CodePudding user response:

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();

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

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