< Summary

Information
Class: MyNet.Reflection.ReflectionComparer<T>
Assembly: MyNet.Reflection
File(s): https://raw.githubusercontent.com/sandre58/MyNet/85372080fe102cd9ee155ceab49ae000e7f66103/src/MyNet.Reflection/ReflectionComparer.cs
Tag: 323_28699572109
Line coverage
93%
Covered lines: 14
Uncovered lines: 1
Coverable lines: 15
Total lines: 55
Line coverage: 93.3%
Branch coverage
77%
Covered branches: 17
Total branches: 22
Branch coverage: 77.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Compare(...)100%11100%
Compare(...)77.27%222292.85%

File(s)

https://raw.githubusercontent.com/sandre58/MyNet/85372080fe102cd9ee155ceab49ae000e7f66103/src/MyNet.Reflection/ReflectionComparer.cs

#LineLine coverage
 1// -----------------------------------------------------------------------
 2// <copyright file="ReflectionComparer.cs" company="Stéphane ANDRE">
 3// Copyright (c) Stéphane ANDRE. All rights reserved.
 4// </copyright>
 5// -----------------------------------------------------------------------
 6
 7using System;
 8using System.Collections;
 9using System.Collections.Generic;
 10using System.ComponentModel;
 11
 12namespace 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>
 18public class ReflectionComparer<T>(IList<ReflectionSortDescription> sortDescriptions) : IComparer, IComparer<T>
 19{
 20    /// <inheritdoc />
 621    public int Compare(object? x, object? y) => Compare((T?)x, (T?)y);
 22
 23    /// <inheritdoc />
 24    public int Compare(T? x, T? y)
 25    {
 1526        var result = 0;
 27
 4528        foreach (var item in sortDescriptions)
 29        {
 1230            var obj1 = x?.GetDeepPropertyValue(item.Path);
 1231            var obj2 = y?.GetDeepPropertyValue(item.Path);
 32
 1233            result = obj1 switch
 1234            {
 935                IComparable toCompare1 => toCompare1.CompareTo(obj2),
 336                null => obj2 != null ? -1 : 0,
 037                _ => obj2 != null ? 1 : -1
 1238            };
 1239            result *= item.Direction == ListSortDirection.Descending ? -1 : 1;
 40
 1241            if (result != 0)
 42            {
 943                break;
 44            }
 45        }
 46
 1547        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>
 54public record ReflectionSortDescription(string Path, ListSortDirection Direction = ListSortDirection.Ascending);
 55