JP Hellemons Building E-commerce web applications

Filter a DataTable with LINQ to Objects

3. October 2011 05:44by JP Hellemons in C#
Today I had a DataTable object with the top x rows of a query. select top 23 * from products So my Asp.Net C# code looked like this: private void SampleMethod(int toShow) { string sql = "SELECT top " + toShow + " * from products"; SqlCommand com = new SqlCommand(sql); DataTable dt = dal.GetDataTable(com); if (dt.Rows.Count > 0) { var a = dt.AsEnumerable().Where( p => p.Field<int>("stock") > p.Field<int>("ProductMinStock")) DataList2.DataSource = a; DataList2.DataBind(); } } This crashed as you might have noticed. The error was:More...