I have a list of names. The list will contain multiple similar names, like {“Stanley”, “Stanley”, “Andy”, “Andy”}. How do I find the length of duplicate items, so I can check if there is more than one of them?
Maybe i am dragging this too far, but i was curious about possible solutions for this in C# and the following imho is a cool way, cause you do not have to monkey around with loops, Dictionaries, whatever to create the result and you can also apply further filtering, ordering etc. to the result.
So one way to get the occurrence count for each element in a list is to use GroupBy() from the Linq namespace:
...
using System.Linq;
...
List<string> names = new List<string>() { "Stanley", "Stanley",
"Andy", "Andy", "Mary" };
var groups = names.GroupBy(inputString => inputString);
foreach (var group in groups)
{
// check for duplicates
if (group.Count() > 1)
{
Debug.Log(group.Key + ": " + group.Count());
}
}
The argument to GroupBy() defines the key for each group, in this example ( inputString => inputString
) each occurring input value is unchanged for the key generation, so each name in the list is a key. If you, for example, want to check how many names in the list start with an ‘A’, inputString => inputString.StartsWith('A')
will generate the groups/keys true
(starts with an ‘A’) and/or false
(doesn’t) and their according counts.
See this question on StackOverflow for this and other possible solutions.
And if you want to avoid duplicates, you can use a HashSet instead of a List, as @andrew-lukasik already suggested.