Order by problem in List (linq related)
I have a problem on how to order a list. I have a list of products and i sort them by price. But in my db i have two prices : price and offer.
I want to sort my products by price , BUT if offer is >0 then 开发者_JS百科i want to sort by offer
I thought of this but it does not work:
list.OrderBy(p => p.offer != 0 ? p.offer : p.price );
Any ideas??
As someone has said, OrderBy
doesn't sort in place. It returns a IOrderedEnumerable
(it's something similar to an IEnumerable
, but ordered :-) ).
If you want to sort in place (and you are using a List<>
) do this:
list.Sort((p, q) => (p.offer != 0 ? p.offer : p.price).CompareTo(q.offer != 0 ? q.offer : q.price));
Maybe you can create a new list that contains a field called final price which is equal to offer if offer > 0, otherwise with price. Then sort, and then get the final list.
var new_list = list.Select(element => new { new_price = element.offer > 0 ? element.offer : element.price, element });
var ordered_new_list = new_list.OrderBy(element => element.new_price);
var ordered_List = ordered_new_list.Select(element => element.element);
OrderBy
does not sort in-place. It returns an ordered sequence without modifying the original. You need to assign the result:
var sortedList = list.OrderBy(p => p.offer > 0 ? p.offer : p.price).ToList();
精彩评论