I'm using .NET 4.5 in C#, and I've got two collections of different classes that I'm trying to compare. They have some columns with similar names, but they don't implement a common interface (and can't for coding-standard reasons).
The first class looks like this:
class Foo
{
string Key1 {get; set;}
string Key2 {get; set;}
string NotKey {get; set;}
string AlsoNotKey {get; set;}
}
While the second one looks like this:
class Bar
{
string Key1 {get; set;}
string Key2 {get; set;}
}
What I want to do is pass a collection of Foo
into a method and return true
when every distinct pair of Key1
and Key2
in it has a match in a collection of Bar
retrieved from a database (via EF), but I can't figure out how to do that.
My first idea looked something like this...
//IEnumerable<Foo> foos
//DbSet<Bar> bars
foos.All(foo => foo.Key1 == bars.Key1 && foo.Key2 == bars.Key2)
...but it doesn't work because bars
is a collection too, and I can't just use Contains()
around each column because then it won't compare both columns as a pair.
In SQL, I could do something like
SELECT COUNT(*)
FROM foos
JOIN bars
ON foos.key1 = bars.key1
AND foos.key2 = bars.key2
and compare it to the number of records in foos
by itself, but how can I translate that to LINQ?
Edit: Found this related question. How to use linq `Except` with multiple properties with different class?
Might try something like this, unless there's a better way.
foos.All(f => bars.Any(b => f.Key1 == b.Key1 && f.Key2 == b.Key2))