Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading