简体   繁体   中英

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).

This is the linq-sql that I used:

  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.

Can I used orderby twice in my query?

The correct syntax has the orderby keyword once; 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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM