I have that class
public class jQGridModel
{
public List<jQGridModelItem> Items { get; set; }
public class jQGridModelItem
{
public DBUser UserItem { get; set; }
public int ItemsSold { get; set; }
}
}
and the DBUser class (generated by Entity Framework)
public class DBUser
{
public string UserName { get; set; }
public string UserID { get; set; }
public string PromoCode { get; set; }
...
}
I have jQGridModel object with some Items. And here’s the ‘simple’ problem – I want to sort the Items list asc/desc basing on the UserName
I’ve tried
jQGridModel result = new jQGridModel();
result.Items = GetItems();
result.Items = result.Items.OrderByDescending(x => x.UserItem.UserName).ToList();
but I see that the collenction order does’t change. What am I doing wrong ?
The complete code:
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();
I should have said it “doesn’t return an IQueryable”, which it doesn’t. So, you get your list in the order you get it, then you are trying to order by a (most likely) lazy loaded property. So you aren’t really doing what you think you are doing. 🙂
Either place the UserName as a property of the jQGridModelItem, or if you really need the full DBUser entity, you can load it up first, then sort.EDIT
Actually, just specify the proper ordering in the initial orderby: