c# - Using Linq to group by multiple columns in a list and mark all duplicate items -
using linq i'd query list , find duplicate persons (a duplicate defined having same first, last name , date of birth) , mark each of duplicate person's stateofdata property string "duplicate" , each unique person's stateofdata property string "unique".
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 persons list should read:
"diane","jones","1967-01-01","duplicate"
"diane","jones","1967-01-01","duplicate"
"john","jones","1967-01-01","unique"
any appreciated
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; } }
Comments
Post a Comment