Langage de programmation orienté objet et sécurisé au niveau des types, qui prend ses racines dans la famille des langages C et inclut la prise en charge de la programmation orientée vers les composants.
How to avoid unnecessary evaluations in LINQ queries using OrderBy followed by multiple ThenBy clauses
AL CHAMI Zaher
0
Points de réputation
Hello,
Here is a simplified example:
using System;
using System.Linq;
class Program
{
static void Main()
{
var data = new[]
{
new { Name = "Alice", Age = 30 },
new { Name = "Bob", Age = 25 },
new { Name = "Charlie", Age = 25 }
};
var sorted = data
.OrderBy(x => Tracer("First criterion", x.Age))
.ThenBy(x => Tracer("Second criterion", x.Name));
foreach (var item in sorted)
{
Console.WriteLine($"{item.Name} - {item.Age}");
}
}
static T Tracer<T>(string label, T value)
{
Console.WriteLine($"Computing {label} key: {value}");
return value;
}
}
// Output displayed on the screen:
// Computing First criterion key: 30
// Computing First criterion key: 25
// Computing First criterion key: 25
// Computing Second criterion key: Alice
// Computing Second criterion key: Bob
// Computing Second criterion key: Charlie
// Bob - 25
// Charlie - 25
// Alice - 30
We can observe that LINQ evaluates the second criterion (ThenBy) for all elements, and not only for those that remain after the first OrderBy. In other words, the sort keys of all ThenBy clauses are computed for the entire collection.
Is there a way to work around this behavior?
Thank you in advance.
Kind regards,
Technologies de développement | C#
Technologies de développement | C#
Se connecter pour répondre