count duplicates in a collection in csharp

To count duplicates in a collection in C#, you can use LINQ to group the elements by their value, and then count the number of items in each group greater than one. Here's an example using a List<string>:

main.cs
List<string> list = new List<string> { "apple", "banana", "cherry", "apple", "date", "banana", "apple" };

var duplicates = list
    .GroupBy(s => s) // group by value
    .Where(g => g.Count() > 1) // select groups with count greater than 1
    .Select(g => new { Value = g.Key, Count = g.Count() }); // select value and count

foreach (var duplicate in duplicates)
{
    Console.WriteLine($"Value: {duplicate.Value}, Count: {duplicate.Count}");
}
449 chars
12 lines

This will output:

main.cs
Value: apple, Count: 3
Value: banana, Count: 2
47 chars
3 lines

This approach can be used with any type of collection and any type of element, as long as the element type implements Equals and GetHashCode correctly.

gistlibby LogSnag