HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How to Sort a List<T> by a property in the object

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
propertyobjecthowsortthelist

Problem

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:
List objListOrder = new List();
GetOrderList(objListOrder); // fill list of orders


I want to sort the list based on one property of the Order object; for example, either by OrderDate or OrderID.

How can I do this in C#?

Solution

The easiest way I can think of is to use Linq:

List SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();

Code Snippets

List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();

Context

Stack Overflow Q#3309188, score: 2347

Revisions (0)

No revisions yet.