Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ef 4.1 LINQ filter an element into a collection

I am using entity framework code first. I have a collection let's say:

 IDbSet<A> As {get;set;}

A is an object like this:

 public class A
 {
    public int Id {get;set;}
    public string name {get;set};
    ....
    public IList<B> Bs {get;set;}
 }

and B is:

 public clas B
 {
    public int Id {get;set;}
    public string name {get;set;}
 }

Using linq I want to filter the As which contains B.name == "something" in its IList so how to achieve this? I am trying to do something like:

context.As.Where(a => a.Bs.contains(....));
like image 875
Ralph Avatar asked Dec 06 '25 17:12

Ralph


2 Answers

You can use Any()

context.As.Where(a => a.Bs.Any(b => b.name == "something").ToList();

It takes a predicate and returns upon a match making it efficient.

like image 123
David L Avatar answered Dec 08 '25 09:12

David L


I would use the Any() method.

var result = context.As.Where(a => a.Bs.Any(b => b.Name == "something"));
like image 41
Maarten Avatar answered Dec 08 '25 08:12

Maarten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!