| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ReflectionComparer.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections; |
| | | 9 | | using System.Collections.Generic; |
| | | 10 | | using System.ComponentModel; |
| | | 11 | | |
| | | 12 | | namespace MyNet.Reflection; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Compares objects by reflecting on specified property paths and applying the provided sort descriptions. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <typeparam name="T">The type of objects to compare.</typeparam> |
| | | 18 | | public class ReflectionComparer<T>(IList<ReflectionSortDescription> sortDescriptions) : IComparer, IComparer<T> |
| | | 19 | | { |
| | | 20 | | /// <inheritdoc /> |
| | 6 | 21 | | public int Compare(object? x, object? y) => Compare((T?)x, (T?)y); |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | | 24 | | public int Compare(T? x, T? y) |
| | | 25 | | { |
| | 15 | 26 | | var result = 0; |
| | | 27 | | |
| | 45 | 28 | | foreach (var item in sortDescriptions) |
| | | 29 | | { |
| | 12 | 30 | | var obj1 = x?.GetDeepPropertyValue(item.Path); |
| | 12 | 31 | | var obj2 = y?.GetDeepPropertyValue(item.Path); |
| | | 32 | | |
| | 12 | 33 | | result = obj1 switch |
| | 12 | 34 | | { |
| | 9 | 35 | | IComparable toCompare1 => toCompare1.CompareTo(obj2), |
| | 3 | 36 | | null => obj2 != null ? -1 : 0, |
| | 0 | 37 | | _ => obj2 != null ? 1 : -1 |
| | 12 | 38 | | }; |
| | 12 | 39 | | result *= item.Direction == ListSortDirection.Descending ? -1 : 1; |
| | | 40 | | |
| | 12 | 41 | | if (result != 0) |
| | | 42 | | { |
| | 9 | 43 | | break; |
| | | 44 | | } |
| | | 45 | | } |
| | | 46 | | |
| | 15 | 47 | | return result; |
| | | 48 | | } |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | /// <summary> |
| | | 52 | | /// Describes a property path and direction to use when comparing via <see cref="ReflectionComparer{T}"/>. |
| | | 53 | | /// </summary> |
| | | 54 | | public record ReflectionSortDescription(string Path, ListSortDirection Direction = ListSortDirection.Ascending); |
| | | 55 | | |