Reputation: 1065
I have 2 classes
public class ClassA
{
public int Id { get; set; }
public string Name { get; set; }
}
And
public class ClassB
{
public int Id { get; set; }
public string Name { get; set; }
public ClassA ClassA { get; set; }
}
I am trying to filter a list of ClassB with a List of Class A
void Main()
{
var ListA = new List<ClassA>();
var a1 = new ClassA() {Id=1, Name = "A1"};
var a2 = new ClassA() {Id=2, Name = "A2"};
var a3 = new ClassA() {Id=3, Name = "A3"};
ListA.Add(a1);
ListA.Add(a2);
ListA.Add(a3);
var FilterListA = new List<ClassA>();
FilterListA.Add(a1);
FilterListA.Add(a2);
var ListB = new List<ClassB>();
var b1 = new ClassB() {Id=1, Name="B1" ,ClassA= a1};
var b2 = new ClassB() {Id=1, Name="B1", ClassA= a2};
var b3 = new ClassB() {Id=1, Name="B1", ClassA= a3};
var b4 = new ClassB() {Id=1, Name="B1", ClassA= a3};
ListB.Add(b1);
ListB.Add(b2);
ListB.Add(b3);
ListB.Add(b4);
it works if I use
var query = from b in ListB
join a in FilterListA
on b.ClassA equals a
select new { Name = b.Name, ClassAName = a.Name };
Console.WriteLine(query.ToList());
But I would like to do something like this... but i don't know how
Console.WriteLine(ListB.Where(o => o.ClassA IsIncluded In FilterListA));
}
I tried using Contains without success. thanks
Upvotes: 0
Views: 4592
Reputation: 23087
This should works:
ListB.Where(x=>FilterListA.Any(y=>y==x.ClassA));
It gets all elements from ListB which have equivalent element in FilterListA. If object of ClassA included in element of list is listed in FilterListA it's returned.
EDIT:
as gunr2171 said you can use Contains
ListB.Where(x=>FilterListA.Contains(x.ClassA));
Upvotes: 3