C# LINQ Where


This entry is part 4 of 4 in the series C# LINQ

This post explores a few examples of how to use a filter, Where, with LINQ. Here are a few examples.

  • Contains
  • StartsWith
  • Equals
  • EndsWith

1class Product
2{
3    public string Name { get; set; }
4    public float Price { get; set; }
5}
6class ProductRepository
7{
8    public IEnumerable<Product> GetProducts()  // method
9    {
10        return new List<Product>
11        {
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},
15        };
16    }
17}
18class Program
19{
20    static void Main(string[] args)
21    {
22        var products = new ProductRepository().GetProducts();
23        var pricyProducts = new List<Product>();
24        // ------without LINQ----------------------------
25        foreach (var product in products)
26        {
27            if (product.Price > 10)
28                pricyProducts.Add(product);
29        }
30        // ------without LINQ-----------------------------
31        foreach (var product in pricyProducts)
32           Console.WriteLine("{0} {1:C}",product.Name, product.Price);
33    }
34}

If we use LINQ we can replace the “without LINQ” commented code with the code below.

1// -----with LINQ-------------------------------------------
2var pricyProducts2 = products.Where(p => p.Price > 10);
3// -----with LINQ-------------------------------------------
Series Navigation<< C# LINQ Array of Integers