1

Let's say we have 2 sets

A = [ PersonA,PersonB];

B = [ ManagerZ,ManagerT,ManagerY];

Result : ManagerT,ManagerY

There exists One to One mapping between the objects in A and the objects in B. I'm interested in those objects in B for which exists such an entry in A.

For completeness let's say we are matching on property named Name

Christo S. Christov
  • 2,268
  • 3
  • 32
  • 57

4 Answers4

3

You have to perform a join on both lists:

var query =
    from person in persons
    join manager in managers on person.Name equals manager.Name
    select new { Person = person, Manager = manager };

This will select all data from your Person-dataset together with the corresponding data from Manager-dataset.

Alternativly you can flatten the results into a datatype providing the whole data for every match:

    select new { Name = person.Name, Age = person.Age, Departement = Manager.Departement }

Or if you´re only interested on the items from B which match use simply select manager.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Argumentation why I didn't accept your answer : I was looking for something simpler than the answer I accepted. This adds a lot of boilerplate code. I assume the complexity of either solutions is O(N^2) so I would always take the simpler one. If I'm wrong and there is some optimization from your approach I would gladly take your answer. Thanks – Christo S. Christov Jan 25 '16 at 13:55
  • This could result in duplicate manager objects if there are multiple name matches with the person list. – juharr Jan 25 '16 at 14:13
3

Try following

SetB.Where(b => SetA.Any(a => a.Name == b.Name))
tchelidze
  • 8,050
  • 1
  • 29
  • 49
1

Try with this code:

List<BType> result = B.Where(x >= A.Exists(y => y.Name == x.Name)).ToList();

In this way you mantain only managers that exists in people list.

erikscandola
  • 2,854
  • 2
  • 17
  • 24
  • Should be noted that this only works if `A` is a `List` as `Exists` is an instance method of `List`. – juharr Jan 25 '16 at 14:11
1

Also you can use Intersect. Example:

public class Person
{
    public string Name { get; set; }
}

public class PersonEqualityComparer : IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {
        return x.Name.Equals(x.Name);
    }

    public int GetHashCode(Person obj)
    {
        return obj.Name.GetHashCode();
    }
}

And now you can use:

var persons = new List<Person>() { new Person { Name = "John" } };
var managers = new List<Person>() { new Person { Name = "John" } };
var results = persons.Intersect(managers, new PersonEqualityComparer());

If you want compare two different class just edit Comparer.

Jiri Sykora
  • 484
  • 4
  • 10