Linq and C#, Skipping records, casting error
I'm trying to skip and take from a query, but get the casting errors:
Error 1 Cannot implicitly convert type 'System.Linq.IQueryable<tblComment>' to 'System.Linq.IOrderedQueryable<tblComment>'. An explicit conversion exists (are you missing a cast?)
Error 2 Cannot implicitly convert type 'System.Linq.IQueryable<tblComment>' to 'System.Linq.IOrderedQueryable<tblComment>'. An explicit conversion exists (are you missing a cast?)
On the lines:
if(ToSkip > 0)
q = q.Skip(ToSkip);
if(ToTake > 0)
q = q.Take(ToTake);
Here's the full method, any help is appreciated! All I'm trying to do is filter the records returned down if they are specified to do so.
Also, is this a good way of doing it, or will the database return ALL the records every time? Ie, will it fetch all the records, THEN do the skip and take? I want to make it efficient.
/// <summary>
/// Fetches all comments from a category
/// </summary>
/// <param name="Category">Category ID of comments to fetch</param>
/// <param name="Identifier">Identifier ID for category</param>
/// <param name="ToTake">How many to take in query. 0 = all</param>
/// <param name="ToSkip">How many to开发者_如何学C skip.</param>
/// <returns></returns>
public static Comment[] FetchCommentsByNewest(int Category, int Identifier, int ToSkip, int ToTake)
{
Comment[] Comments = new Comment[1];
using (DataClassesDataContext db = new DataClassesDataContext())
{
// Loop each comment and insert newest first to array
var q = (from c in db.tblComments where c.CategoryID == Category && c.IdentifierID == Identifier orderby c.PostDate descending select c);
if(ToSkip > 0)
q = q.Skip(ToSkip);
if(ToTake > 0)
q = q.Take(ToTake);
Comments = new Comment[q.Count()];
int i = 0;
foreach (var Rec in q)
{
i++;
}
}
return Comments;
}
You could always bypass it by changing the code into this:
var q = (
from c in db.tblComments
where c.CategoryID == Category && c.IdentifierID == Identifier
orderby c.PostDate descending select c
)
.Skip(ToSkip > 0 ? ToSkip : 0)
.Take(ToTake > 0 ? ToTake : int.MaxValue);
Use the same logic as ChrisF showed and finish the statement with return q.ToArray() or if you need a model class e.g. Comment then use something like AutoMapper http://automapper.codeplex.com/
or
return q.select( x=> new Comment{Name = x.Name, Description = x.Description}).ToArray();
Note: the ToArray or ToList() will cause the query to be executed.
精彩评论