Reputation: 484
I have two list of objects. For e.g. say the objects are like below
class A
{
int ID;
int Value;
}
class B
{
int ID;
int Value;
}
I have two list of above objects like List<A> AList
and List<B> BList
. I want to find if any object in List<B>
has matching Value from List<A>
.
For now, what I do like is
foreach(var item in AList)
{
if(!BList.Any(x => x.Value == item.Value))
{
//Handle the error message
}
}
Is there any better way to do it by Linq?
Upvotes: 0
Views: 68
Reputation: 1151
This is what I've tried and it seems to work just fine:
class First
{
public int Id { get; set; }
public int Value { get; set; }
}
class Second
{
public int Id { get; set; }
public int Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
var firstList = new List<First>
{
new First { Id = 1, Value = 2 },
new First { Id = 1, Value = 10 },
new First { Id = 1, Value = 0 }
};
var secondList = new List<Second>
{
new Second { Id = 1, Value = 2 },
new Second { Id = 1, Value = 2 },
new Second { Id = 1, Value = 4 }
};
bool hasCommonValues = firstList.Select(f => f)
.Any(u => secondList.Select(x => x.Value)
.Contains(u.Value));
Console.WriteLine(hasCommonValues);
}
}
Upvotes: 1
Reputation: 89325
According to your current code, and if you just need to handle error when any item in AList
doesn't have a matching item in BList
, you can do as follows :
if (AList.Any(a => !BList.Any(b => b.Value == a.Value)))
{
//Handle error
}
Or if you need to take an action on every item in AList
that doesn't have a matching item in BList
:
foreach(var item in AList.Where(a => !BList.Any(b => b.Value == a.Value)))
{
//Handle error for current `item`
}
Anyways, the reason to prefer LINQ over conventional foreach
loop is usually more for its readability (shorter, cleaner, easier to maintain, etc.) rather than performance. For reference : Is a LINQ statement faster than a 'foreach' loop?
Upvotes: 1
Reputation: 1507
Try this:
BList.Any(b => AList.Any(a => a.Value == b.Value));
Upvotes: 1
Reputation: 9165
You can do it this way. This will be true if there are any items in BList that have matching values in AList:
BList.Any(b => AList.Select(a => a.Value).Contains(b.Value))
Upvotes: 1
Reputation: 8462
Simply:
from a in AList
join b in BList on a.Value equals b.Value
select a
Upvotes: 1