This post explores a few examples of how to use a filter, Where, with LINQ. Here are a few examples.
- Contains
- StartsWith
- Equals
- EndsWith

3 | public string Name { get ; set ; } |
4 | public float Price { get ; set ; } |
8 | public IEnumerable<Product> GetProducts() |
10 | return new List<Product> |
12 | new Product() {Name = "P one" , Price = 5}, |
13 | new Product() {Name = "P two" , Price = 9.99f}, |
14 | new Product() {Name = "P three" , Price = 12}, |
20 | static void Main( string [] args) |
22 | var products = new ProductRepository().GetProducts(); |
23 | var pricyProducts = new List<Product>(); |
25 | foreach (var product in products) |
27 | if (product.Price > 10) |
28 | pricyProducts.Add(product); |
31 | foreach (var product in pricyProducts) |
32 | Console.WriteLine( "{0} {1:C}" ,product.Name, product.Price); |
If we use LINQ we can replace the “without LINQ” commented code with the code below.
2 | var pricyProducts2 = products.Where(p => p.Price > 10); |