views:

141

answers:

3

i have an object called Person. It has properties First, Last, Age, etc . . .

I have two arrays of Person objects.

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

+3  A: 

Here is a linq function (IEnumerable<T>.Except(...)) that will do what you need.

http://msdn.microsoft.com/en-us/library/bb336390.aspx

Daniel A. White
That is actually awesome.
Alex Bagnolini
@Alex - LINQ is awesome.
Daniel A. White
You should probably add that he would need to compare the objects for equality, either by implementing a comparer, or doing the comparison within the lambda. Except on its own will not solve the problem.
Winston Smith
The link is to the one with the `IEqualityComparer`.
Daniel A. White
A: 

Implement IComparable (see SO: IComparable and Equals) and then loop through each list, building the required two output lists.

Jim H.
Linq will do this for you.
Daniel A. White
+1  A: 

You could write a comparer (implement the IEqualityComparer interface) then use it with the Except extension method, as other posters have noted.

Or, you could just do the comparison within the lambda eg

var peopleinFirstListAndNotSecond =     
    firstList.
    Where( p => 
            !secondList.Any( s => 
                s.Age == p.Age && 
                s.FirstName == p.FirstName && 
                s.SecondName == p.SecondName
         ) 
    );
Winston Smith