Answer the question
In order to leave comments, you need to log in
Sorting in LINQ to SQL
There is a task to display ... well, for example, products in the online store section.
LINQ to SQL is used.
I am writing code like this:
List lstGoods = DataContext.Sections.Where(x=>x.id = iMySectionId).First().Goods.Take(iPageSize).ToList();
List lstGoods = DataContext.Sections.Where(x=>x.id = iMySectionId).First().Goods.OrderBy(x=>x.Name).Take(iPageSize).ToList();
List lstGoods = null ;
if (sSortField == "name" )
{
if (sSortDirection == "ASC" )
{
lstGoods = DataContext.Sections.Where(x=>x.id = iMySectionId).First().Goods.OrderBy(x=>x .Name).Take(iPageSize).ToList();
}
else
{
lstGoods = DataContext.Sections.Where(x=>x.id = iMySectionId).First().Goods.OrderByDescending(x=>x.Name).Take(iPageSize).ToList();
}
}
List lstGoods = DataContext.Sections.Where(x=>x.id = iMySectionId).First().Goods.ToList();
if (sSortField == "name" )
{
if (sSortDirection == "ASC" )
{
lstGoods = lstGoods .OrderBy(x=>x.Name).Take(iPageSize);
}
else
{
lstGoods = lstGoods .OrderByDescending(x=>x.Name).Take(iPageSize);
}
}
Answer the question
In order to leave comments, you need to log in
Here is a working class that I have already used
http://aonnull.blogspot.com/2010/08/dynamic-sql-like-linq-orderby-extension.html
LINQ query is executed directly at its usage stage (ToList(), foreach, etc.), and not at the formation stage.
code:
var allGoods = DataContext.Sections.Where(x=>x.id = iMySectionId).First().Goods;
List lstGoods = allGoods.OrderBy(x=>x.Name).OrderByDescending(x=>x.Price).Take(iPageSize).ToList();
will execute one query...
as an option, you can use reflection, though you still need to think about optimization. reflection thing is not fast.
List<Person> list = new List<Person>();
list.Add(new Person() { Age = 20, Name="Вася"});
list.Add(new Person() { Age = 21, Name = "Петя" });
list.Add(new Person() { Age = 23, Name = "Коля" });
list.Add(new Person() { Age = 18, Name = "Саша" });
PropertyInfo pi = new Person().GetType().GetProperty("Name");
List<Person> sorted = list.OrderBy(p=> pi.GetValue(p, null)).ToList();
List<Person> list = new List<Person>();
list.Add(new Person() { Age = 20, Name = "Вася" });
list.Add(new Person() { Age = 21, Name = "Петя" });
list.Add(new Person() { Age = 23, Name = "Коля" });
list.Add(new Person() { Age = 18, Name = "Саша" });
string propertyName = "Age";
ParameterExpression parameterExpr =
Expression.Parameter(typeof(Person), "person");
Expression<Func<Person, object>> orderByExpr =
Expression.Lambda<Func<Person, object>>(
Expression.TypeAs(
Expression.Property(
parameterExpr, propertyName), typeof(object)), parameterExpr);
Func<Person, object> orderByFunc = orderByExpr.Compile();
List<Person> sorted = list.OrderByDescending(p => orderByFunc(p)).ToList();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question