Tuesday, February 18, 2014

LINQ - Filter a List from a comma separated string

I've used a sample Product class shown below.  productList contains 3 static values.

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}


string productIds = "1,3";
List<Product> productList = new List<Product>();

productList.Add(new Product() { Name = "iPhone", Price = 60000, ProductId = 1 });
productList.Add(new Product() { Name = "Google Nexus 5", Price = 34000, ProductId = 2 });
productList.Add(new Product() { Name = "iPad", Price = 27000, ProductId = 3 });


ProductIds are split into an IEnumerable<int> array and LINQ WHERE clause is used with "Contains"

//split productIds and populate productIdArray
IEnumerable<int> productIdArray = productIds.Split(',').Select(x => int.Parse(x));

//filter productList and fetch only the records which contains values in "productIdArray"
IEnumerable<Product> productFilter = productList.Where(c => productIdArray.Contains(c.ProductId));

No comments: