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));

"Children could not be evaluated" issue after updating Entity Framework to version 6

I was recently working on an ASP.NET MVC 4 website using Entity Framework 5.0.  

I updated my entity framework using "update-package -EntityFramework" command in package manager console.  It updated Entity Framework pretty well, but stuck me with an issue.  I was no longer able to debug my values and it showed "Children could not be evaluted" as shown below.  This was working fine before I updated my entity framework.








The solution is really simple but tricky.  I just had to add .ToList() at the end of the query and it worked like a charm.