16

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.

2

4 Answers 4

39

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.)

Sign up to request clarification or add additional context in comments.

Comments

2

Don't ever use non-generic collections in C# when you can use generics instead. There are a lot of reasons to use generic collections only (except for very special cases).

See this question for more info: When would you not use Generic Collections?

So you can use List<PropertyDetails> (which I believe exposes a Sort() method) or SortedList<,>.

Comments

1

Using linq you can crate a new sorted list:

list.OrderBy(x => x.Sequence).ToList();

If you want to sort your current list, you can use a comparer:

list.Sort((details1, details2) => details1.Sequence.CompareTo(details2.Sequence);

1 Comment

This is not "in place", and is less efficient as it must create an entirely new collection.
-1
var sortedList = propertyDetailsList.OrderBy(pd => pd.Sequence);

4 Comments

Is actually not sorting the list, but creating a new IEnumerable which contains the sorted items... I still think that this is the requested solution.
It is not a "sortedList". It is a "IOrderableEnumerable<T>". It needs a .ToList() to make an actual "sortedList".
hence the use of "var", sortedList is just the variable name
I feel compelled to point out that calling something sortedList and then using var to hide the fact that it's not, in fact, a sorted list is just really bad practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.