0

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.