Buda Gavril Buda Gavril - 3 months ago 16
C# Question

Linq: find elements with common properties but different types

I have two list with objects:

class Class1
public int Id { get; set; }
public string Name { get; set; }
public Guid UniqueIdentifier { get; set; }
public bool IsValid { get; set; }

class Class2
public int Identifier { get; set; }
public string Producer{ get; set; }
public Guid Guid { get; set; }
public int SupplierId { get; set; }

Is there a way to use
to get the elements of type
from the list that have the same
(identifier) and
with the elements of type
from the second list?


Here is one way to do it:

var result = list1
    .Where(x => list2.Any(y => x.Id == y.Identifier && x.UniqueIdentifier == y.Guid))

Please note that this version is not optimized for large lists. If your lists are small, this is fine. If you have large lists, you need a solution that involves things like HashSets. Here is an example:

var list2HashSet = CreateHashset(list2.Select(x => new {x.Identifier, x.Guid}));

var result = list1
    .Where(x => list2HashSet.Contains(new {Identifier = x.Id, Guid = x.UniqueIdentifier}))

Where CreateHashset is defined like this:

public static HashSet<T> CreateHashset<T>(IEnumerable<T> collection)
    return new HashSet<T>(collection);

I had to create this simple method because the compiler is complaining that it cannot resolve the correct constructor overload. I am not really sure why.