-1

I've got a class called "Order" that has a "Order Number" and a "Weight".

I've got a list of orders that is unorganized. I'd like to sort this List by the weight of each order. Ascending and Descending.

        {
            return new List<Order>() {
             new Order(){
             OrderNumber =1,
             Weight = 1.2
            },
             new Order(){
             OrderNumber =2,
             Weight = 1.2
            },
             new Order(){
             OrderNumber =3,
             Weight = 1.2
            },
             new Order(){
             OrderNumber =4,
             Weight = 2
            },
             new Order(){
             OrderNumber =5,
             Weight = 1.2
            },
             new Order(){
             OrderNumber =6,
             Weight = 1.2
            }
            };
        }

I would want to create a List OrganizedOrders in which the heaviest (Order Number 4) would be at the top of this list.

Thank you a lot. I know this is very basic but i'm just getting started. Thanks!

  • 4
    Does this answer your question? [How to Sort a List by a property in the object](https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – madreflection Jan 16 '20 at 00:01

2 Answers2

0

@Luciano try using a lambda expression. Where your list is called myOrders:

myOrders.OrderBy(o => o.Weight);

Or for descending:

myOrders.OrderByDescending(o => o.Weight);

Either of which you could save into a new list if you really need to:

List<Order> ascendingOrders = myOrders.OrderBy(o => o.Weight).ToList();
Michael
  • 412
  • 3
  • 12
-1

This has been asked before (How to Sort a List<T> by a property in the object)

Use LINQ:

List<Order> SortedList = myOrderList.OrderBy(o=>o.Weight).ToList();

or

List<Order> SortedList = myOrderList.OrderByDescending(o=>o.Weight).ToList();
Bryan Lewis
  • 5,629
  • 4
  • 39
  • 45
  • 3
    Please flag duplicates instead of creating duplicate answers, especially when you found the duplicate already. – madreflection Jan 16 '20 at 00:02
  • 2
    Agreed! If you know it's a duplicate you can click the `close` link, choose `Duplicate of...` and then paste in the link to the dup. – Rufus L Jan 16 '20 at 00:05