概括而不丢失类型

时间:2017-01-10 15:43:44

标签: c# linq linq-to-sql generalization

我需要将这两种方法合并在一起进行概括。我知道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规则并且非常烦人。

1 个答案:

答案 0 :(得分: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;
    }
}