Suppose you have a model that describes the structure of a single record in a file:
class Example { public string X { get; set; } public string Y { get; set; } public string W { get; set; } public string H { get; set; } public string A { get; set; } }
And the file has already been read and written to the collection, for example
IEnumerable<Example> exampleCollection
Then you can sort the collection using LINQ to Object:
- OrderBy - sorts the elements of a sequence in ascending order
- OrderByDescending - sorts the elements of a sequence in descending order
- ThenBy - performs additional ordering of sequence elements in ascending order.
- ThenByDescending - performs additional ordering of sequence elements in descending order.
In your case, to sort by two columns, use:
exampleCollection = exampleCollection.OrderBy(e => eY).ThenBy(e => eA);
Attention! This query uses deferred execution.
What does this code do?
This code sorts the collection in ascending order by the Y field; if the Y fields are equal, then additional sorting is performed in the A field, as well as in ascending order.