Tuesday, April 15, 2008

List.FindAll - C# .Net 3.5

In my recent blog post Generics List.FindAll (to filter), I wrote about how I use the FindAll method with anonymous delegates to filter a list. Well, that was C# 2 way. Framework 3.5 onwards with Linq, we could use the power of lambda expressions to even simplify this concept.

using System.Linq;

public IEnumerable<Product> GetProductsNamedLike(List<Product> productList, string nameLike)

{

return productList.Where(p => p.Name.Contains(nameLike));

}

// Not using lambda:

public IEnumerable<Product> GetProductsNamedLike(List<Product> productList, string nameLike)

{

IEnumerable<Product> products = from Product p in productList

where p.Name.Contains(nameLike)

select p;

return products;

}


Love coding!

2 comments:

Unknown said...

Perfect. Thanks

vishal said...

Hi,
What about nested list objects?

UserList contains a list of User item; and each User item contains a list of Product item.
UserList->Users->Products->Product

And we want to filter by product Name="xxx"

How is it possible with lamda expression?