c# - Linq - group each class -
i need removing duplicates form emailaddresses list. need add code group emailaddresses within emailaddresses class. sql returning duplicate email addresses because of different telephone numbers. suggestions? thanks.
here code: 1. classes
public class student { public string studentid { get; set; } public string gender { get; set; } public list<emailaddresses> emailaddresses { get; set; } } public class emailaddresses { public string emailaddress { get; set; } }
2. data coming sql query
studentid emailaddresses ispreferred number telephonetype 123456789 maryjoe@gmail.com false 5556565 present evening phone 123456789 maryjoe@gmail.com false 8885566 permanent day phone 123456789 mary.joe@cuu.edu true 5556565 present evening phone 123456789 mary.joe@cuu.edu true 8885566 permanent day phone 456789123 dh@mycollege.edu true 7513150 business day phone 456789123 donna.hill@cu.edu true 4123300 present day phone 456789123 donna.hill@cu.edu false 4123300 present day phone
3. code
public list<student> getstudentdata() { list<student> datastudent; using (idbconnection connection = repositoryhelper.openconnection()) { datastudent = connection.query<dynamic>( "mystoredprocedure", commandtype: commandtype.storedprocedure) .groupby(x => x.studentid) .select(x => new student { studentid = x.first().studentid, gender = x.first().gender, emailaddresses = x.select(ea => new emailaddresses { emailaddress = ea.emailaddresses }).tolist() }).tolist(); return datastudent; } }
while preferable filter out duplicates before returning, increases complexity of code. if result set small, memory , cpu overhead of filtering after you've returned data may suffer-able , results need. can use custom iequalitycomparer
check distinct results , create new emailaddresses list on each student record contains distinct email addresses.
public list<student> getstudentdata() { list<student> datastudent; using (idbconnection connection = repositoryhelper.openconnection()) { datastudent = connection.query<dynamic>( "mystoredprocedure", commandtype: commandtype.storedprocedure) .groupby(x => x.studentid) .select(x => new student { studentid = x.first().studentid, gender = x.first().gender, emailaddresses = x.select(ea => new emailaddresses { emailaddress = ea.emailaddresses }).tolist() }).tolist(); datastudent.foreach(x => x.emailaddresses = x.emailaddresses .distinct(new studentemailequalitycomparer()).tolist()); return datastudent; } } public class studentemailequalitycomparer : iequalitycomparer<emailaddresses> { public bool equals(emailaddresses x, emailaddresses y) { return x.emailaddress.equals(y.emailaddress); } public int gethashcode(emailaddresses obj) { return obj.emailaddress.gethashcode(); } }
Comments
Post a Comment