Linq和C#,跳过记录,投射错误

时间:2011-04-14 22:57:36

标签: c# asp.net linq casting

我正在尝试跳过并从查询中获取,但得到了转换错误:

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

在线:

if(ToSkip > 0)
    q = q.Skip(ToSkip);
if(ToTake > 0)
    q = q.Take(ToTake);

这是完整的方法,任何帮助表示赞赏!我想要做的就是过滤掉指定的记录,直到它们为止。

此外,这是一种很好的方法,还是数据库每次都会返回所有记录?即,它会获取所有记录,然后跳过并采取?我希望提高效率。

/// <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 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;
}

2 个答案:

答案 0 :(得分:2)

您可以通过将代码更改为此来绕过它:

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

答案 1 :(得分:0)

使用与ChrisF相同的逻辑并使用返回q.ToArray()完成语句,或者如果需要模型类,例如评论 然后使用AutoMapper http://automapper.codeplex.com/

之类的东西

return q.select( x=>  new Comment{Name = x.Name, Description = x.Description}).ToArray();

注意: ToArray或ToList()将导致执行查询。