[英]how to compare two arrays of objects
i have an object called Person . 我有一个名为Person的对象。 It has properties First, Last, Age , etc .
它有First,Last,Age等属性。 .
。 .
。
I have two arrays of Person objects. 我有两个Person对象数组。
I want to have some function to take two arrays 我想要一些函数来获取两个数组
Person[] firstlist = . .
Person[] secondList = . .
and have it spit out two new arrays 让它吐出两个新阵列
Person[] peopleinFirstListandNotSecond
Person[] peopleinSecondListandNotFirst
Since these are not string arrays, i would want to do a compare on first and last name and age to determine if its the same person 由于这些不是字符串数组,我希望对名字和姓氏进行比较以确定它是否是同一个人
Here is a linq function ( IEnumerable<T>.Except(...)
) that will do what you need. 这是一个linq函数(
IEnumerable<T>.Except(...)
), IEnumerable<T>.Except(...)
你的需要。
http://msdn.microsoft.com/en-us/library/bb336390.aspx http://msdn.microsoft.com/en-us/library/bb336390.aspx
You could write a comparer (implement the IEqualityComparer interface ) then use it with the Except extension method, as other posters have noted. 您可以编写一个比较器(实现IEqualityComparer接口 ),然后将其与Except扩展方法一起使用,正如其他海报所述。
Or, you could just do the comparison within the lambda eg 或者,您可以在lambda中进行比较,例如
var peopleinFirstListAndNotSecond =
firstList.
Where( p =>
!secondList.Any( s =>
s.Age == p.Age &&
s.FirstName == p.FirstName &&
s.SecondName == p.SecondName
)
);
实现IComparable(参见SO:IComparable和Equals ),然后遍历每个列表,构建所需的两个输出列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.