gpt4 book ai didi

asp.net - 使用 Entity Framework 对Gridview进行排序。

转载 作者:行者123 更新时间:2023-12-04 03:40:59 24 4
gpt4 key购买 nike

我有办法

private void BindGrid()
{
dataContext = new VTCEntities();
string SortExpression = "DisplayName";
string SortDirection = "ASC";
int skip = 0;

if (this.ViewState["SortExp"] != null)
{
SortExpression = this.ViewState["SortExp"].ToString();
}

if (this.ViewState["SortOrder"] != null)
{
string d = this.ViewState["SortOrder"].ToString();
if (d == "ASC")
{
SortDirection = "ASC";
}
else
{
SortDirection = "DESC";
}
}

if (CurrentPage != 0)
{
skip = CurrentPage * PageSize;
}

if (SortDirection == "ASC")
{
this.grdCustomers.DataSource = dataContext.CustomerSet.OrderBy(i => i.DisplayName).Skip(skip).Take(PageSize);
}
else
{
this.grdCustomers.DataSource = dataContext.CustomerSet.OrderByDescending(i => i.DisplayName).Skip(skip).Take(PageSize);
}

this.grdCustomers.DataBind();
}

而且开始闻起来很臭。我必须对4列进行排序。我想避免进行切换或其他操作来确定我要订购的CustomerSet上的哪个属性。更好的程序员该怎么做才能将SortExpression(一个字符串)与我的CustomerSet对象之一的属性相关联?

一如既往的感谢。
吉姆

最佳答案

我过去曾使用此扩展方法:

public static class QueryExtensions {
public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName) {
if (source == null) {
throw new ArgumentNullException("source");
}

// DataSource control passes the sort parameter with a direction
// if the direction is descending
int descIndex = propertyName.IndexOf(" DESC");

if (descIndex >= 0) {
propertyName = propertyName.Substring(0, descIndex).Trim();
}

if (String.IsNullOrEmpty(propertyName)) {
return source;
}

ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty);
MemberExpression property = Expression.Property(parameter, propertyName);
LambdaExpression lambda = Expression.Lambda(property, parameter);

string methodName = (descIndex < 0) ? "OrderBy" : "OrderByDescending";

Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName,
new Type[] { source.ElementType, property.Type },
source.Expression, Expression.Quote(lambda));

return source.Provider.CreateQuery<T>(methodCallExpression);
}
}

资料来源: http://weblogs.asp.net/davidfowler/archive/2008/12/11/dynamic-sorting-with-linq.aspx

然后,您可以将其重写为:
        if (SortDirection == "ASC")
{
this.grdCustomers.DataSource = dataContext.CustomerSet.OrderBy(i => i.DisplayName).Skip(skip).Take(PageSize);
}
else
{
this.grdCustomers.DataSource = dataContext.CustomerSet.OrderByDescending(i => i.DisplayName).Skip(skip).Take(PageSize);
}


this.grdCustomers.DataSource = dataContext.CustomerSet.SortBy("DisplayName DESC").Skip(skip).Take(PageSize);

关于asp.net - 使用 Entity Framework 对Gridview进行排序。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3945645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com