用于排序和分页的 LINQ to SQL 扩展方法

发布于 2024-07-13 18:34:54 字数 1268 浏览 3 评论 0原文

我找到了一种扩展方法,可以处理 LINQ 的排序和分页。 虽然这很有效,但我正在尝试看看是否还有其他方法可以使用它。

目前,扩展方法的代码如下:

public static IQueryable<T> Page<T, TResult>(
  this IQueryable<T> obj, 
  int page, 
  int pageSize, 
  System.Linq.Expressions.Expression<Func<T, TResult>> keySelector, 
  bool asc, 
  out int rowsCount)
{
    rowsCount = obj.Count();

    int innerRows = (page - 1) * pageSize;

    if (asc)
        return obj.OrderBy(keySelector).Skip(innerRows).Take(pageSize).AsQueryable();
    else
        return obj.OrderByDescending(keySelector).Skip(innerRows).Take(pageSize).AsQueryable();
}

该方法接收一个表达式,这是基于类型的。

在我的 Dealer 类中,我有一个方法 GetDealers,它本质上调用了这个方法, 即,

db.User.Page(1, 2, p => p.User.UserProperty.Name, true, out rowCount)

从事物的表示方面来看,我不知道或无法访问上面的表达式,例如,

ListView1.DataSource = users.GetDealers("SortColumn", pageNo, pageSize, out rowCount, bool asc);
ListView1.DataBind();

唯一的方法是在我的 GetDealers 方法中使用 switch 语句,然后将其转换为表达式。 有没有办法绕过这个,或者这个方法可以吗?

I have found an extension method that handles sorting and paging for LINQ. While this works well, I am trying to see if there are some other ways I can use this.

At present, the code for the extension method is as follows:

public static IQueryable<T> Page<T, TResult>(
  this IQueryable<T> obj, 
  int page, 
  int pageSize, 
  System.Linq.Expressions.Expression<Func<T, TResult>> keySelector, 
  bool asc, 
  out int rowsCount)
{
    rowsCount = obj.Count();

    int innerRows = (page - 1) * pageSize;

    if (asc)
        return obj.OrderBy(keySelector).Skip(innerRows).Take(pageSize).AsQueryable();
    else
        return obj.OrderByDescending(keySelector).Skip(innerRows).Take(pageSize).AsQueryable();
}

The method takes in an expression, which is based off the type.

In my Dealer class, I have a method GetDealers, which essentially calls this,
i.e.

db.User.Page(1, 2, p => p.User.UserProperty.Name, true, out rowCount)

From the presentation side of things though, I do not know or can access the expression as above, e.g.

ListView1.DataSource = users.GetDealers("SortColumn", pageNo, pageSize, out rowCount, bool asc);
ListView1.DataBind();

The only way is to have a switch statement in my GetDealers method that would then convert to the expression. Is there a way to bypass this, or is this method OK?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦年海沫深 2024-07-20 18:34:54

我不太确定你在问什么,但我相信这是我自己研究过的。 如果您想知道如何根据字符串而不是正确的 LINQ 表达式对结果进行动态排序,那么您很幸运。

Scott Guthrie 发表了一篇很棒的关于该主题的文章。 它引用了一个 Microsoft 文件,该文件扩展了任何 IQueryable 对象以支持动态排序。
C# 动态查询库(包含在 \LinqSamples\DynamicQuery 目录中) 。 只需将该页面添加到您的 App_Code 文件夹中,并在您的项目中包含“Using System.Linq.Dynamic”,您就可以使用以下语法:

myUsers = myUsers.OrderBy("LastName");

我希望这会有所帮助!

I'm not exactly sure what you're asking, but I believe it's something that I have looked into myself. If you would like to know how to dynamically sort your results based on a string, rather than a proper LINQ expression, then you're in luck.

Scott Guthrie published a great article on that very topic. It references a Microsoft file which extends any IQueryable object to support dynamic sorting.
C# Dynamic Query Library (included in the \LinqSamples\DynamicQuery directory). Just add the page to your App_Code folder and include "Using System.Linq.Dynamic" in your project and you will be able to use the following syntax:

myUsers = myUsers.OrderBy("LastName");

I hope this helps!

执手闯天涯 2024-07-20 18:34:54

如果您正在寻找适用于所有类型的扩展方法

public static class SortingAndPagingHelper
{
    /// <summary>
    /// Returns the list of items of type on which method called
    /// </summary>
    /// <typeparam name="TSource">This helper can be invoked on IEnumerable type.</typeparam>
    /// <param name="source">instance on which this helper is invoked.</param>
    /// <param name="sortingModal">Page no</param>
    /// <returns>List of items after query being executed on</returns>
    public static IEnumerable<TSource> SortingAndPaging<TSource>(this IEnumerable<TSource> source, SortingAndPagingInfo sortingModal)
    {
        // Gets the coloumn name that sorting to be done o`enter code here`n
        PropertyInfo propertyInfo = source.GetType().GetGenericArguments()[0].GetProperty(sortingModal.SortColumnName);

        // sorts by ascending if sort criteria is Ascending otherwise sorts descending
        return sortingModal.SortOrder == "Ascending" ? source.OrderByDescending(x => propertyInfo.GetValue(x, null)).Skip(sortingModal.PageSelected * sortingModal.PageSize).Take(sortingModal.PageSize)
                           : source.OrderBy(x => propertyInfo.GetValue(x, null)).Skip(sortingModal.PageSelected * sortingModal.PageSize).Take(sortingModal.PageSize);
    }
}

DbContext dbContext = new DbContext();
dbContext.rainingSessions.Where(x => x.RegistrationDeadline > DateTime.Now) .SortingAndPaging(sortAndPagingInfo).ToList()

If you are looking for extension method to work on all types

public static class SortingAndPagingHelper
{
    /// <summary>
    /// Returns the list of items of type on which method called
    /// </summary>
    /// <typeparam name="TSource">This helper can be invoked on IEnumerable type.</typeparam>
    /// <param name="source">instance on which this helper is invoked.</param>
    /// <param name="sortingModal">Page no</param>
    /// <returns>List of items after query being executed on</returns>
    public static IEnumerable<TSource> SortingAndPaging<TSource>(this IEnumerable<TSource> source, SortingAndPagingInfo sortingModal)
    {
        // Gets the coloumn name that sorting to be done o`enter code here`n
        PropertyInfo propertyInfo = source.GetType().GetGenericArguments()[0].GetProperty(sortingModal.SortColumnName);

        // sorts by ascending if sort criteria is Ascending otherwise sorts descending
        return sortingModal.SortOrder == "Ascending" ? source.OrderByDescending(x => propertyInfo.GetValue(x, null)).Skip(sortingModal.PageSelected * sortingModal.PageSize).Take(sortingModal.PageSize)
                           : source.OrderBy(x => propertyInfo.GetValue(x, null)).Skip(sortingModal.PageSelected * sortingModal.PageSize).Take(sortingModal.PageSize);
    }
}

DbContext dbContext = new DbContext();
dbContext.rainingSessions.Where(x => x.RegistrationDeadline > DateTime.Now) .SortingAndPaging(sortAndPagingInfo).ToList()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文