Brand new to C#, ASP.NET Core and web development in general. I'm trying to implement a generic method that I can reuse with the JQuery DataGrid. The method is as follows:
protected String ItemsToJson(IQueryable items, List<String> columnNames, String sort, String order, Int32 limit, Int32 offset)
{
try
{
Int32 count = items.Count();
String sortExpression = "";
if (sort != null && sort.Length > 0)
sortExpression += String.Format("{0} {1}", sort, order);
if (limit == 0)
limit = count;
var result = new
{
total = count,
rows = items.OrderBy(sortExpression).Skip(offset).Take(limit).Select("new (" + String.Join(",", columnNames) + ")")
};
return JsonConvert.SerializeObject(result, Formatting.None, new JsonSerializerSettings() { MetadataPropertyHandling = MetadataPropertyHandling.Ignore });
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
The line reading Int32 count = items.Count(); returns the following error:
'IQueryable' does not contain a definition for 'Count' and no accessible extension method 'Count' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?)
The line reading rows = Items.OrderBy(sortExpression)..... returns the following error:
'IQueryable' does not contain a definition for 'OrderBy' and no accessible extension method 'Count' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?)
I have a using for System.Linq. Any thoughts? It's driving me crazy!
Thanks bunch.
--- Val
What is the type of item provided by the IQueryable items
?
The Count method is available against IQueryable<T>
, meaning if you change the incoming parameter to IQueryable<SomeType> items
, you should be able to access it.
https://learn.microsoft.com/en-us/dotnet/api/system.linq.iqueryable-1
The
IQueryable
interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implementIQueryable<T>
. If the provider does not also implementIQueryable<T>
, the standard query operators cannot be used on the provider's data source.