Home > Software engineering >  How to get duplicate values in List<object> using LINQ C#
How to get duplicate values in List<object> using LINQ C#

Time:09-27

Below is my sample List of object.

Person1: Id=1, Name="Test1", Lastname="Test1", Age=13
Person2: Id=2, Name="Test2", Lastname="Test2", Age=14
Person3: Id=3, Name="Test1", Lastname="Test1", Age=15
Person4: Id=4, Name="Test4", Lastname="Test4", Age=16

I want to get the duplicate from the List by querying the Name and Lastname.

My new list should be Person1 and Person3.

Person1: Id=1, Name="Test1", Lastname="Test1", Age=13
Person3: Id=3, Name="Test1", Lastname="Test1", Age=15

How do I achieve this one using LINQ?

CodePudding user response:

You can groupBy by multiple properties, Name and Lastname. And apply Where on the result with Count>1, unwind the groups with SelectMany and convert it back to List.

public static void Main(string[] args)
{
    var persons = new List<Person>
    {
        new Person{ Id=1, Name="Test1", Lastname="Test1", Age=13 },
        new Person{ Id=2, Name="Test2", Lastname="Test2", Age=14 },
        new Person{ Id=3, Name="Test1", Lastname="Test1", Age=15 },
        new Person{ Id=4, Name="Test4", Lastname="Test4", Age=16 }
    };

    List<Person> filteredPersons = persons
        .GroupBy(d => new { d.Name, d.Lastname })
        .Where(g => g.Count() > 1)
        .SelectMany(g => g.ToList())
        .ToList();

    filteredPersons.ForEach(x => Console.WriteLine($"{x.Id}: {x.Name} {x.Lastname} {x.Age}"));
}

The output will be

1: Test1 Test1 13
3: Test1 Test1 15
  • Related