Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort List<T> in c# / .net

Tags:

c#

list

sorting

I have a class PropertyDetails:

public class PropertyDetails
{

     public int Sequence { get; set; }

     public int Length { get; set; }

     public string Type { get; set; }
}

I am creating a list of PropertyDetails as

List<PropertyDetails> propertyDetailsList=new List<PropertyDetails>();

I want to sort this list by PropertyDetails.Sequence.

Linq solutions are welcome.

like image 697
PramodChoudhari Avatar asked Jan 18 '11 12:01

PramodChoudhari


People also ask

Can you sort a list C#?

Sorting in C# In C#, we can do sorting using the built-in Sort / OrderBy methods with the Comparison delegate, the IComparer , and IComparable interfaces.

Does the sort () method modify the underlying list?

Yes the List<T>. Sort method does indeed sort the collection in place and hence modifies the collection.


1 Answers

If you want to sort the existing list in-place then you can use the Sort method:

List<PropertyDetails> propertyDetailsList = ...
propertyDetailsList.Sort((x, y) => x.Sequence.CompareTo(y.Sequence));

If you want to create a new, sorted copy of the list then you can use LINQ's OrderBy method:

List<PropertyDetails> propertyDetailsList = ...
var sorted = propertyDetailsList.OrderBy(x => x.Sequence).ToList();

(And if you don't need the results as a concrete List<T> then you can omit the final ToList call.)

like image 93
LukeH Avatar answered Oct 14 '22 23:10

LukeH