Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting duplicate data based on dynamic key

Tags:

c#

linq

I have a list of Person objects:

List<PersonData> AllPersons

From this list I want all those person objects that are duplicated based on a certain property.

Example, this code give all the duplicates based on the Id

var duplicateKeys = AllPersons.GroupBy(p => p.Id).Select(g => new { g.Key, Count = g.Count() }).Where(x => x.Count > 1).ToList().Select(d => d.Key);
    duplicates =  AllPersons.Where(p => duplicateKeys.Contains(p.Id)).ToList();

Can the part p.Id be dynamic?

Meaning if the user specifies the unique column in a config file and it's read like so:

string uniqueColumn = "FirstName";

How can the query be composed to add that functionality?

Regards.

like image 571
Codehelp Avatar asked Dec 12 '25 16:12

Codehelp


1 Answers

You can use Reflection to achieve that:

List<PersonData> AllPersons = new List<PersonData>()
{
    new PersonData { Id = 1, FirstName = "Tom" },
    new PersonData { Id = 2, FirstName = "Jon" },
    new PersonData { Id = 3, FirstName = "Tom" }
};

string uniqueColumn = "FirstName";

var prop = typeof(PersonData).GetProperty(uniqueColumn);

var duplicateKeys = AllPersons.GroupBy(p => prop.GetValue(p, null))
                              .Select(g => new { g.Key, Count = g.Count() })
                              .Where(x => x.Count > 1)
                              .Select(d => d.Key)
                              .ToList();

var duplicates = AllPersons.Where(p => duplicateKeys.Contains(prop.GetValue(p, null))).ToList();

duplicates have 2 elements with FirstName == "Tom" after query execution.

like image 111
MarcinJuraszek Avatar answered Dec 15 '25 05:12

MarcinJuraszek