LINQ Interview Question #136

How can LINQ be used to find duplicate values?

Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

Group elements by the value or key that defines duplication, then retain groups whose Count is greater than one. The key identifies the duplicated value, and the group can provide the duplicate records.

Detailed Explanation

Group elements by the value or key that defines duplication, then retain groups whose Count is greater than one. The key identifies the duplicated value, and the group can provide the duplicate records.

For simple scalar values, GroupBy is usually sufficient. For objects, group by a property such as Email, SKU, or another business key.

Code Example

var duplicates = users
    .GroupBy(u => u.Email)
    .Where(g => g.Count() > 1)
    .Select(g => new
    {
        Email = g.Key,
        Count = g.Count()
    });