LINQ provides us operator for different tasks such as selection,filtering,ordering.Usually we filter and select the same type as the original type when working with LINQ.
In many scenarios we want to filter and map items to a different list type.For example we are performing LINQ operations on a list of type Product and we want to add the filtered products to a list of string.
In the following example we have a list of Product.We are filtering the items in Product list.We are filtering the items whose price is more than 50.We are using the x => x.Price > 50 lambda expression for this.
Where(x => x.Price > 50)
After we filter the items we are adding the string elements to a list of string type
string.Format("Id: {0} Name: {1} Price: {2}", x.Id, x.Name, x.Price)
Below is the complete example
List<Product> products = new List<Product>(); products.AddRange(new List<Product>{ new Product { Id = 1, Name = "Headset", Price = 100 }, new Product { Id = 2, Name = "Mic", Price = 50 }, new Product { Id = 3, Name = "TV", Price = 1000 } } ); List<string> lstProducts = new List<string>(); products.Where(x => x.Price > 50).Select(x => x).ToList().ForEach(x => { lstProducts.Add(string.Format("Id: {0} Name: {1} Price: {2}", x.Id, x.Name, x.Price)); }); foreach(var product in lstProducts) { Console.WriteLine(product); } Console.ReadLine();
Output:
Leave a Reply