1

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?

2 Answers 2

1

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; 
0
0

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

2
  • @MMatteo Mosca: So how about order by ascending? Commented Dec 15, 2011 at 8:17
  • +1. Just a remark: even though you are correct, it is quite simply a matter of taste and the final result is the same (also in performance). Commented Dec 15, 2011 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.