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.
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.
Yes the List<T>. Sort method does indeed sort the collection in place and hence modifies the collection.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With