2012-01-13 70 views
2

我有2個領域的排序:產品名稱和價格加2選項:升序或降序。如何在Linq orderby中執行「if」?

用戶可以通過設置2個複選框來指定排序順序:打開或關閉價格複選框和打開或關閉複選框。

當基於上述2個複選框的設置動態設置排序順序時,如何編碼orderby子句?謝謝。

回答

6

您可以通過有條件地指定OrderBy子句構建查詢:

var query = from product in db.Products select product; 

if(price.Checked && ascending.Checked) 
{ 
    query = query.OrderBy(product => product.Price); 
} 
else if(price.Checked && !ascending.Checked) 
{ 
    query = query.OrderByDescending(product => product.Price); 
} 
else if(!price.Checked && ascending.Checked) 
{ 
    query = query.OrderBy(product => product.Name); 
} 
else 
{ 
    query = query.OrderByDescending(product => product.Name); 
} 
2

請注意,下面的ascendingCondition是基於你的代碼

if(ascendingCondition) 
{ 
    ProductCollection.OrderBy(p => p.Name).ThenBy(p => p.Price) 
} 
else 
{ 
    ProductCollection.OrderByDescending(p => p.Name).ThenByDescending(p => p.Price) 
}