This post explores a few examples of how to use a filter, Where, with LINQ. Here are a few examples.
- Contains
- StartsWith
- Equals
- EndsWith
class Product { public string Name { get; set; } public float Price { get; set; } } class ProductRepository { public IEnumerable<Product> GetProducts() // method { return new List<Product> { new Product() {Name = "P one", Price = 5}, new Product() {Name = "P two", Price = 9.99f}, new Product() {Name = "P three", Price = 12}, }; } } class Program { static void Main(string[] args) { var products = new ProductRepository().GetProducts(); var pricyProducts = new List<Product>(); // ------without LINQ---------------------------- foreach (var product in products) { if (product.Price > 10) pricyProducts.Add(product); } // ------without LINQ----------------------------- foreach (var product in pricyProducts) 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.
// -----with LINQ------------------------------------------- var pricyProducts2 = products.Where(p => p.Price > 10); // -----with LINQ-------------------------------------------