1

I have a List<B> and class B has a public property A.

How can I filter the list of B using a Predicate<A>?

0

3 Answers 3

5

If your list is named myList and your predicate myPredicate, then you want probably something like this:

var result = myList.Where(b => myPredicate(b.A))

or you can use a lambda expression, e.g.:

var result = myList.Where(b => b.A < 10)

or something like this, where the predicate would be b.A < 10.

Maybe you should give us a more complete code sample.

2
  • This is what I was looking for myList.FindAll(b=>yourPredicate(b.A)) thanks
    – wilsonlarg
    Mar 12, 2012 at 12:30
  • function call is more scallable then inline lambda
    – Tigran
    Mar 12, 2012 at 12:32
3

If you are using Linq, you can do this:

// Define the predicate inline:
var results = list.Where(b => b.A.Name == "Fred");

// or if you have the predicate defined separately:
var results = list.Where(b => predicate(b.A));

If you are not using Linq, you can use the FindAll method on the System.Collections.Generic.List class:

var results = list.FindAll(predicate);
0
list.Where(i=>i.B == "something")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.