learning
learning

Reputation: 11735

How to compare arrays?

I am having a class Employee with properties Name and ID

I am having an array Employee[] A an another array Employee[] B. How can I compare the two arrays and remove the the values not present in B from A?

Upvotes: 0

Views: 200

Answers (5)

trkll666
trkll666

Reputation: 1

Employee[]  c = (from d in a where !b.Contains<Employee>(d) select d).ToArray<Employee>();

Upvotes: 0

vc 74
vc 74

Reputation: 38179

To illustrate Jason's suggestion (comparison based on IDs):

class IDEmployeeComparer : IEqualityComparer<Employee>
{
    public bool Equals(Employee first, Employee second)
    {
      return (first.ID == second.ID);
    }

    public int GetHashCode(Employee employee)
    {
       return employee.ID
    }
}

...

var intersection = A.Intersect(B, new IDEmployeeComparer ()).ToArray();

Jon Skeet's misc library allows specifying the comparer inline without having to create a separate class

Upvotes: 0

whjou
whjou

Reputation: 156

I think you can find some inspiration from http://msdn.microsoft.com/en-us/library/wdka673a.aspx aka the RemoveAll() method. You'll need to put the arrays into Lists, but that shouldn't stump you...

Upvotes: 0

user582955
user582955

Reputation: 1

Can you use System.Collections.Generic?

I would do something like:

var listA = new List<Employee>(A);
var listB = new List<Employee>(B); //not sure if arrays implement contains, may not need this line

A = listA.where(e => listB.Contains(e)).toArray();

Hope that helps.

Upvotes: 0

jason
jason

Reputation: 241769

var intersection = A.Intersect(B).ToArray();

Note that this uses the default IEqualityComparer<Employee> which is just going to be a reference comparison unless you've overridden Equals and GetHashCode. Alternatively, you could implement IEqualityComparer<Employee> and use the overload of Intersect that takes in instance of IEqualityComparer<Employee>.

Upvotes: 7

Related Questions