我正在寻找一种比较2种不同List<>的优雅方式。集合并删除特定字段值匹配的项目。例如: 客户对象
class Customer
{
string CustomerName;
string Email;
}
class Employee
{
string EmployeeName;
string EmployeeID;
}
List<Customer> Customers = new List<Customers(GetCustomers());
List<Employee> Employees = new List<Employees(GetEmployees());
然后我知道我可以通过这样做从Employees列表中删除Customers列表中的Employe:
Employees.RemoveAll(e => Customers.Any(c.CustomerName == e.EmployeeName));
我想知道的是我如何从客户列表中删除相应的员工?是否可以使用简单的语句或者我是否需要构建一些来处理这个问题?
答案 0 :(得分:1)
怎么样:
Employees.Where(e => Customers.Any(c=> c.CustomerName == e.EmployeeName)).ToList()
.ForEach(e=> {
Employees.Remove(e);
Customers.RemoveAll(c => c.CustomerName == e.EmployeeName);
});
答案 1 :(得分:0)
创建一个要删除的所有客户的列表,以及首先要删除的所有员工中的另一个。然后从原始列表中删除所有这些内容。我对lambda没有足够的认识从记忆中写出来,但它应该是可行的。
答案 2 :(得分:0)
试试吧:
List<Customer> c = new List<Customer>();
c.Add(new Customer() {CustomerName = "test", Email = "email" });
c.Add(new Customer() { CustomerName = "test1", Email = "email1" });
c.Add(new Customer() { CustomerName = "test2", Email = "email2" });
c.Add(new Customer() { CustomerName = "test3", Email = "email3" });
List<Employee> e = new List<Employee>();
e.Add(new Employee() { EmployeeName = "test2", EmployeeID = "1" });
e.Add(new Employee() { EmployeeName = "test1", EmployeeID = "2" });
e.Add(new Employee() { EmployeeName = "test5", EmployeeID = "3" });
e.Add(new Employee() { EmployeeName = "test4", EmployeeID = "4" });
//remove from the Customers list the corresponding Employee
e.RemoveAll(x => c.Any(y => y.CustomerName == x.EmployeeName));
foreach (var employee in e)
{
//TODO:
}
答案 3 :(得分:0)
var inBoth = customers.Join(employees, customer => customer.CustomerName, employee => employee.EmployeeName, (customer, employee) => employee.EmployeeName).ToList();
customers.RemoveAll(customer => inBoth.Contains(customer.CustomerName));
employees.RemoveAll(employee => inBoth.Contains(employee.EmployeeName));
答案 4 :(得分:0)
可以这样做:
var toBeDeleted = employees.Select(e => e.EmployeeName)
.Where(name => customers.Any(c => c.CustomerName == name))
.ToList();
customers.RemoveAll(c => toBeDeleted.Contains(c.CustomerName));
employees.RemoveAll(e => toBeDeleted.Contains(e.EmployeeName));
您可以使用Intersect
来获取应删除的元素。我不知道任何一行命令可以做到这一点。