Question:Working with a list of Employees:List<Employee> lstEmployees = new List<Employee>
{
new Employee{Name="Harry",Age=15},
new Employee{Name="Peter",Age=22},
new Employee{Name="John",Age=45},
new Employee{Name="Harry",Age=15},
new Employee{Name="Peter",Age=22},
new Employee{Name="John",Age=45},
};
It is required to filter out employees having distinct names.
Which one of the following options cannot be used?
A public class Employee {
public int Age { get; set; }
public string Name { get; set; }
public override bool Equals(object obj) {
return this.Name.Equals(((Employee)obj).Name);
}
public override int GetHashCode() {
return this.Name.GetHashCode();
}
}
List<Employee> distinctEmployeesByName = lstEmployees.Distinct().ToList();
B public class Employee {
public int Age { get; set; }
public string Name { get; set; }
}
public class EmployeeEquityComparable : IEqualityComparer<Employee> {
#region
IEqualityComparer<Employee> Members public bool Equals(Employee x, Employee y) {
return x.Name.Equals(y.Name);
}
public int GetHashCode(Employee obj) {
return obj.Name.GetHashCode();
}
#endregion
}
List<Employee> distinctEmployeesByName = lstEmployees.Distinct(new EmployeeEquityComparable()).ToList();
C public class Employee:IEqualityComparer<Employee> {
public int Age { get; set; }
public string Name { get; set; }
#region
IEqualityComparer<Employee> Members public bool Equals(Employee x, Employee y) { return x.Name.Equals(y.Name);
}
public int GetHashCode(Employee obj) {
return obj.Name.GetHashCode();
}
#endregion
}
List<Employee> distinctEmployeesByName = lstEmployees.Distinct().ToList();
D public class Employee {
public int Age { get; set; }
public string Name { get; set; }
}
List<Employee> distinctEmployeesByName = (from emp in lstEmployees group emp by emp.Name into gemp select gemp.First()).ToList();