[英]How to sort item selected from database using LinQ to SQL in asp.net mvc c#
I want to sort the price and the quantity of my product that query from database to show in my view. 我想对从数据库查询的产品的价格和数量进行排序,以显示在视图中。 I throw the choice to the parameter string of URL (Products?availability=availabilityLowtoHigh&priceSort=priceLowtoHigh&tab=2).
我将选择扔到URL的参数字符串中(产品?availability = availabilityLowtoHigh&priceSort = priceLowtoHigh&tab = 2)。
This is the linq-sql that I used: 这是我使用的linq-sql:
public IList<Item> Sort(string availability,string priceSort)
{
IEnumerable<Item> ien_item;
if (availability == "availabilityLowtoHigh" && priceSort == "priceLowtoHigh")
{
ien_item = from i in this.DataContext.Items
orderby i.Quantity ascending
orderby i.Price ascending
select i;
}else{
ien_item = from i in this.DataContext.Items
orderby i.Quantity descending
orderby i.Price descending
select i;
}
}
Detail : if the parameter of query string availability == "availabilityLowtoHigh" and priceSort == "priceLowtoHigh", so the product will show in the page by sorting the products that have a less to more quantity, and cheap price to expensive price. 详细信息:如果查询字符串的参数available ==“ availabilityLowtoHigh”和priceSort ==“ priceLowtoHigh”,那么该产品将通过对数量较少,价格从低到高的产品进行排序来显示在页面中。
Can I used orderby twice in my query? 我可以在查询中两次使用orderby吗?
The correct syntax has the orderby keyword once; 正确的语法只有一次orderby关键字; separate multiple orderings with commas:
用逗号分隔多个顺序:
ien_item = from i in this.DataContext.Items
orderby i.Quantity ascending, i.Price ascending
select i;
or 要么
ien_item = from i in this.DataContext.Items
orderby i.Quantity descending, i.Price descending
select i;
The use of linq in your case is highly redundant. 在您的情况下使用linq是高度冗余的。 You can simply write:
您可以简单地写:
ien_item = DataContext.Items
.OrderByDescending(c => c.Quantity)
.ThenByDescending(c => c.Price);
As you can see a simple lambda is more than enough, no need to resort to linq (which would eventually translated to lambda anyway). 如您所见,简单的lambda绰绰有余,无需诉诸linq(无论如何最终都会转换为lambda)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.