1

我有那个课

public class jQGridModel
{
    public List<jQGridModelItem> Items { get; set; }

    public class jQGridModelItem
    {
        public DBUser UserItem { get; set; }
        public int ItemsSold { get; set; }
    }
}

DBUser类(由实体框架生成)

public class DBUser 
{
    public string UserName { get; set; }
    public string UserID { get; set; }
    public string PromoCode { get; set; }
    ...
}

我有jQGridModel一些反对Items。这是“简单”的问题 - 我想Items根据UserName

我试过了

jQGridModel result = new jQGridModel();
result.Items = GetItems();

result.Items = result.Items.OrderByDescending(x => x.UserItem.UserName).ToList();

但我看到收集顺序没有改变。我究竟做错了什么 ?

完整代码:

        var query = (from x in db.User
                     where (...)
                     select x);

        var totalRecords = query.Count();

        jQGridModel result = new jQGridModel();

        result.Items = query.OrderBy(x => x.UserID).Skip(page * pageSize)
                            .Take(pageSize)
                            .Select(x => new jQGridModel.jQGridModelItem
                            {
                                UserItem = x,
                                ItemsSold = (from o in db.Order
                                             where
                                                 o.PromoCode.Equals(x.PromoCode)
                                             select o).Count()
                            })
                            .ToList();


  result.Items = result.Items.OrderByDescending(x => x.UserItem.UserName).ToList();
4

1 回答 1

2

我应该说它“不返回 IQueryable”,但事实并非如此。因此,您按照获取列表的顺序获取列表,然后尝试按(很可能)延迟加载的属性进行排序。所以你并没有真正做你认为你正在做的事情。:)

要么将 UserName 作为 jQGridModelItem 的属性,要么如果你真的需要完整的 DBUser 实体,你可以先加载它,然后排序。

编辑

实际上,只需在初始 orderby 中指定正确的顺序:

result.Items = query.OrderBy(x => x.UserName).Skip(page * pageSize)
                            .Take(pageSize)
                            .Select(x => new jQGridModel.jQGridModelItem
                            {
                                UserItem = x,
                                ItemsSold = (from o in db.Order
                                             where
                                                 o.PromoCode.Equals(x.PromoCode)
                                             select o).Count()
                            })
                            .ToList();
于 2012-12-03T20:33:29.717 回答