asp.net - How Get All duplicate record using linq -
in project i'm having critical problem: have collection of employee
s in collection. of employee
s have same lname
:
public class employee { public int id { get; set; } public string fname { get; set; } public string mname { get; set; } public string lname { get; set; } public datetime dob { get; set; } public char gender { get; set; } } public class myclass { public list<employee> getall() { list<employee> emplist = new list<employee>(); emplist.add(new employee() { id = 1, fname = "john", mname = "", lname = "shields", dob = datetime.parse("12/11/1971"), gender = 'm' }); emplist.add(new employee() { id = 2, fname = "mary", mname = "matthew", lname = "jacobs", dob = datetime.parse("01/17/1961"), gender = 'f' }); emplist.add(new employee() { id = 3, fname = "amber", mname = "carl", lname = "agar", dob = datetime.parse("12/23/1971"), gender = 'm' }); emplist.add(new employee() { id = 4, fname = "kathy", mname = "", lname = "foxsss", dob = datetime.parse("11/15/1976"), gender = 'f' }); emplist.add(new employee() { id = 5, fname = "lena", mname = "ashco", lname = "bilton", dob = datetime.parse("05/11/1978"), gender = 'f' }); emplist.add(new employee() { id = 6, fname = "susanne", mname = "", lname = "buck", dob = datetime.parse("03/7/1965"), gender = 'f' }); emplist.add(new employee() { id = 7, fname = "jim", mname = "", lname = "hooks", dob = datetime.parse("09/11/1972"), gender = 'm' }); emplist.add(new employee() { id = 8, fname = "jane", mname = "g", lname = "hooks", dob = datetime.parse("12/11/1972"), gender = 'f' }); emplist.add(new employee() { id = 9, fname = "robert", mname = "", lname = "fox", dob = datetime.parse("06/28/1964"), gender = 'm' }); emplist.add(new employee() { id = 10, fname = "cindy", mname = "preston", lname = "fox", dob = datetime.parse("01/11/1978"), gender = 'm' }); return emplist; } }
how can duplicate records (based on lname
) collection using linq?
it's not clear, looks you're looking following:
var duplicates = getall().groupby(x => x.lname) .where(g => g.count() > 1) .selectmany(g => g) .tolist()
it groups element lname
, takes groups have more 1 element , returns them list.
duplicates
list<employee>
.
you can make bit better using todictionary
instead of tolist
:
var duplicates = getall().groupby(x => x.lname) .where(g => g.count() > 1) .todictionary(g = > g.key, g.tolist());
it dictionary<string, list<employee>>
, lname
dictionary key, , list of items given lname
value
.
Comments
Post a Comment