Buda Gavril Buda Gavril - 22 days ago 6
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
linq
to get the elements of type
Class1
from the list that have the same
Id
(identifier) and
Guid
with the elements of type
Class2
from the second list?

Answer

Here is one way to do it:

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

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}))
    .ToList();

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.

Comments