基于不同名称的字符串属性将两种不同类型的集合相交
本文关键字:同类型 集合 两种 属性 于不同 字符串 | 更新日期: 2023-09-27 18:27:06
我有一个由两种不同类型的对象组成的集合。
我正在尝试基于字符串属性进行.Intersect。。。。。。
public class EmployeeDto
{
public string SSN { get; set; }
public DateTime HireDate { get; set; }
}
public class PersonDto
{
public string SocialSecurityNumber { get; set; }
public string Name { get; set; }
}
尝试次数:
ICollection<EmployeeDto> empsColl = new List<EmployeeDto>();
empsColl.Add(new EmployeeDto() { SSN = "222-22-2222", HireDate = DateTime.Now });
empsColl.Add(new EmployeeDto() { SSN = "333-33-3333", HireDate = DateTime.Now });
empsColl.Add(new EmployeeDto() { SSN = "444-44-4444", HireDate = DateTime.Now });
empsColl.Add(new EmployeeDto() { SSN = "555-55-5555", HireDate = DateTime.Now });
ICollection<PersonDto> pers = new List<PersonDto>();
pers.Add(new PersonDto() { SocialSecurityNumber = "333-33-3333", Name = "John" });
pers.Add(new PersonDto() { SocialSecurityNumber = "444-44-4444", Name = "Mary" });
ICollection<EmployeeDto> overlap1 = empsColl.Where(api => api.SSN.Any(val => val.Equals(pers.Any(cl => cl.SocialSecurityNumber.Equals(val))))).ToList();
ICollection<EmployeeDto> overlap2 = empsColl.Where(api => api.SSN.Equals(pers.Any(per => per.SocialSecurityNumber.Equals(api.SSN, StringComparison.OrdinalIgnoreCase)))).ToList();
foreach (EmployeeDto emp in overlap1)
{
Console.WriteLine(emp.SSN);
}
所需的结果是一个ICollection<EmployeeDto>
,它包含EmployeeDo对象333-33-3333和444-44-4444。
谢谢。
以下是如何做到这一点:
var overlap = empsColl.Where(e => pets.Any(p => p.SocialSecurityNumber == e.SSN)).ToList();
我认为这可以做到
empsColl.Where(ec => pers.Select(p => p.SocialSecurityNumber).Contains(ec.SSN)));
这应该能在中工作
var result = empsColl.Where(x => pers.Any(y=> string.Compare(y.SocialSecurityNumber, x.SSN) == 0));