Using Linq to group across multiple columns in a list and mark all duplicate items

Using LinQ, I would like to query the list and find duplicates (the duplicate is defined as having the first name, last name and date of birth) and mark each of the duplicate StateOfData property with the string "duplicate" and each unique StateOfData property with a unique string.

public  Class Person 
{
public string PersonFirstName { get; set; }
public string PersonLastName { get; set; }
public datetime PersonDateOfBirth { get; set; }
public string StateOfData{ get; set }

public Person (string firstName, string lastName, dateTime dateOfBirth,string state)
{
    this.PersonFirstName  = firstName;
    this.PersonLastName = lastName;
    this.PersonDateOfBirth = dateOfBirth;
    this.StateOfData = state;
}


}


IList<Person> personsList  =  new List<Person>(); 
Person pers = new Person("Diane","Jones","1967-01-01","");
personsList.add(pers);
Person pers = new Person("Diane","Jones","1967-01-01","");
personsList.add(pers);
Person pers = new Person("John","Jones","1967-01-01","");
personsList.add(pers);

The result of the list of faces should look like this:

"Diana", "Jones", "1967-01-01", "duplicate"
"Diana", "Jones", "1967-01-01", "duplicate"
"John", "Jones", "1967-01 -01 "," unique "

Any help with this would be greatly appreciated.

+3
2
var theLookup = personList
  .GroupBy(p => new {p.PersonFirstName, p.PersonLastName, p.PersonDateOfBirth})
  .ToLookup(g => g.Skip(1).Any() ? "duplicate" : "unique");

foreach(var lookupEntry in theLookup)
{
  string stateOfData = lookupEntry.Key;
  foreach(Person p in lookupEntry.SelectMany(g => g))
  {
    p.StateOfData = stateOfData;
  }
}
+6

Source: https://habr.com/ru/post/1790222/


All Articles