Disclaimer: This is not leetcode implemenation, complexity is not considered. This is looking for an easy implemenation.
Assuming a list of string:
List<string> data = ...
Find out:
- Is there duplications;
- What are the duplications;
- How many times did it duplicated;
List<string> data = new List<string> { "a","e", "c", "b", "c", "c", "d","e" };
IEnumerable<(string Dupe, int Count)> moreThanOnce = data
.GroupBy(d => d) // Group by the value of the strings, using the string value as keys
.Where(g => g.Count() > 1) // For a given key, how many items does it have? If it have more than 1, it's a dup.
.Select(g => (g.Key, g.Count())); // Output the key, and the count as a Triple<string, int>.
// Output. Or could be anything else.
foreach (var item in moreThanOnce)
{
Console.WriteLine($"{item.Dupe}: {item.Count}");
}
List<string> data = new List<string> { "a", "e", "c", "b", "c", "c", "d", "e" };
List<string> distinct = data.Distinct().ToList();
IEnumerable<string> dup = data.Except(distinct); // Not working, it will exclude everything from data.
Console.WriteLine(dup.Any()); // It is always false!