0

我需要将这两种方法合并为一种概括它们的方法。我知道 IQueryable 实现了 IEnumerable,IOrderedQueryable 实现了 IOrderedEnumerable,如果存在第二种方法,第一种方法似乎没用。但是由于某些实体框架的原因,第二个破坏了服务器端查询转换(Linq-to-SQL)

    private static IQueryable<T> Pag<T>(IOrderedQueryable<T> data, int totalRows, int reqLength, int pageNum)
    {
        if (reqLength == 0)
            return data;
        else
        {
            int skipRows = reqLength * (pageNum - 1);
            if (skipRows >= totalRows)
                skipRows = 0;
            int diff = totalRows - skipRows;
            return data.Skip(skipRows).Take(diff > reqLength ? reqLength : diff);
        }
    }

    private static IEnumerable<T> Pag<T>(IOrderedEnumerable<T> data, int totalRows, int reqLength, int pageNum)
    {
        if (reqLength == 0)
            return data;
        else
        {
            int skipRows = reqLength * (pageNum - 1);
            if (skipRows >= totalRows)
                skipRows = 0;
            int diff = totalRows - skipRows;
            return data.Skip(skipRows).Take(diff > reqLength ? reqLength : diff);
        }
    }

这些方法违反了DRY规则,非常烦人。

4

1 回答 1

0

即使代码看起来相同,它们也不适用于相同的类型,也不能使用泛型,因为 where 子句只能 AND 组合多个给定值。

所以你所能做的就是排除计算逻辑,但如果这真的更好的可读性和可维护性真的取决于你的态度。

private static bool TryCalculateRange(int totalCount, int pageLength, int page, out int skip, out int take)
{
    skip = 0;
    take = 0;

    if(pageLength <= 0)
        return false;

    skip = pageLength * (page - 1);

    if(skip >= totalCount)
        skip = 0;

    take = totalCount - skip;

    if(take > pageLength)
        take = pageLength;

    return true;
}

public static IQueryable<T> Pag<T>(IOrderedQueryable<T> data, int totalRows, int reqLength, int pageNum)
{
    int skip;
    int take;

    return TryCalculateRange(totalRows, reqLength, pageNum, out skip, out take))
           ? data.Skip(skip).Take(take)
           : data;
}

public static IEnumerable<T> Pag<T>(IOrderedEnumerable<T> data, int totalRows, int reqLength, int pageNum)
{
    int skip;
    int take;

    return TryCalculateRange(totalRows, reqLength, pageNum, out skip, out take))
           ? data.Skip(skip).Take(take)
           : data;
    }
}
于 2017-01-12T11:16:35.743 回答