« Les méthodes d'extension » : différence entre les versions
Apparence
Ligne 121 : | Ligne 121 : | ||
source.OrderBy(x => propertyDescriptor.GetValue(x)) : | source.OrderBy(x => propertyDescriptor.GetValue(x)) : | ||
source.OrderByDescending(x => propertyDescriptor.GetValue(x)); | source.OrderByDescending(x => propertyDescriptor.GetValue(x)); | ||
} | |||
</filebox> | |||
== IListExtension == | |||
<filebox fn='IListExtension.cs' collapsed> | |||
/// <summary> | |||
/// Update the property value of the items of the collection. | |||
/// </summary> | |||
public static IEnumerable<IReadOnlyCollection<T>> GroupByRange<T>(this List<T> source, int rangeSize) | |||
{ | |||
var result = new Dictionary<int, List<T>>(); | |||
for (var i = 0; i < source.Count; i++) | |||
{ | |||
var groupId = i / rangeSize; | |||
if (result.TryGetValue(groupId, out var list)) | |||
list.Add(source[i]); | |||
else | |||
result[groupId] = [source[i]]; | |||
if (i % rangeSize == 0 && i - 1 > 0) | |||
result[groupId - 1].Add(source[i]); | |||
} | |||
return result.Values.Select(x => x.AsReadOnly()); | |||
} | } | ||
</filebox> | </filebox> |
Version du 1 novembre 2024 à 14:36
Disponible à partir de C# 3, elles permettent d'ajouter des méthodes à une classe ou à une structure sans en modifier son code.
![]() |
|
// Déclaration de la méthode d'extension dans une classe static
public static class StringExtensions
{
/// <summary>
/// A Contains method with a comparison type.
/// </summary>
public static bool Contains(this string source, string value, StringComparison comparisonType)
{
return source.IndexOf(value, comparisonType) >= 0;
}
}
// Utilisation de la méthode d'extension : comparaison de string en ignorant la casse
var monString = "ASTRINGTOTEST";
monString.Contains("string", StringComparison.OrdinalIgnoreCase);
|
Useful extension methods
CollectionExtension
CollectionExtension.cs |
IEnumerableExtension
IEnumerableExtension.cs |
IListExtension
IListExtension.cs |