I have an ICollection<Plante> Jardin which I want to sort according to some property Plante.Taille:
private readonly ICollection<Plante> Jardin;
I use the instance method OrderByDescending :
public void TriDesc()
{
Console.WriteLine("Tri par taille décroissante");
IOrderedEnumerable<Plante> Temp = Jardin.OrderByDescending(a => a.Taille);
Jardin.Clear();
foreach (Plante p in Temp)
{
Console.WriteLine(p.Taille);
Jardin.Add(p);
}
}
What is the problem here?
I tried debugging: Temp is correctly sorted by the method but Jardin is empty at the end.
As remarked in the docs,
OrderByDescending()is implemented using deferred execution:Thus the sorting isn't actually done until you enumerate through
Temp, at which pointJardinwill have been cleared:Instead, you must materialize a copy of
Jardine.g. withToList()before clearing it and re-adding items items:That being said, in C#
ICollection<T>is an interface that can be implemented by unordered collections such asHashSet<T>that do not necessarily preserve the order in which items are added. If you need yourJardincollection to preserve order, consider usingList<T>instead:If you do, it can be sorted in-place using
List<T>.Sort():Notes:
For a list of methods that use deferred execution, see Classification of Standard Query Operators by Manner of Execution (C#): Classification Table
OrderByDescendingis not an instance method, it is an extension method in theSystem.Linq.Extensionsstatic class.