As remarked in the docs, OrderByDescending()
is implemented using deferred execution:
Deferred execution means that the operation is not performed at the point in the code where the query is declared. The operation is performed only when the query variable is enumerated, for example by using a foreach
statement.
Thus the sorting isn't actually done until you enumerate through Temp
, at which point Jardin
will have been cleared:
// Define an ordering for `Jardin` but don't execute it yet.
IOrderedEnumerable<Plante> Temp = Jardin.OrderByDescending(a => a.Taille);
// Clear `Jardin`
Jardin.Clear();
// Execute and enumerate the ordering of `Jardin` (which is now empty):
foreach (Plante p in Temp)
{
Jardin.Add(p);
}
Instead, you must materialize a copy of Jardin
e.g. with ToList()
before clearing it and re-adding items items:
// Create an ordered copy of `Jardin`
var temp = Jardin.OrderByDescending(a => a.Taille).ToList();
// Clear `Jardin`
Jardin.Clear();
// Add the ordered items back:
foreach (var p in temp)
{
Jardin.Add(p);
}
That being said, in C# ICollection<T>
is an interface that can be implemented by unordered collections such as HashSet<T>
that do not necessarily preserve the order in which items are added. If you need your Jardin
collection to preserve order, consider using List<T>
instead:
private readonly List<Plante> Jardin;
If you do, it can be sorted in-place using List<T>.Sort()
:
// Sort Jardin in descending order of Taille
Jardin.Sort((x, y) => -x.Taille.CompareTo(y.Taille));
Notes: