| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="PropertyAccessorCache.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.Concurrent; |
| | | 9 | | using System.Linq; |
| | | 10 | | using System.Linq.Expressions; |
| | | 11 | | using MyNet.Primitives; |
| | | 12 | | |
| | | 13 | | namespace MyNet.Reflection; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Caches compiled property accessors for sorting properties to improve performance when sorting by property names. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <typeparam name="T">Type of object.</typeparam> |
| | | 19 | | public static class PropertyAccessorCache<T> |
| | | 20 | | { |
| | 3 | 21 | | private static readonly ConcurrentDictionary<string, Func<T, object?>> Cache = new(); |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Gets a compiled property accessor for the specified property name, using a cache to improve performance. If the |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="propertyName">The name of the property for which to get the accessor.</param> |
| | | 27 | | /// <returns>A function that accesses the specified property.</returns> |
| | 15 | 28 | | public static Func<T, object?> Get(string propertyName) => Cache.GetOrAdd(propertyName, Create); |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Creates a compiled property accessor for the specified property name, using expression trees to generate a funct |
| | | 32 | | /// </summary> |
| | | 33 | | /// <param name="propertyName">The name of the property for which to create the accessor.</param> |
| | | 34 | | /// <returns>A function that accesses the specified property.</returns> |
| | | 35 | | private static Func<T, object?> Create(string propertyName) |
| | | 36 | | { |
| | 9 | 37 | | var param = Expression.Parameter(typeof(T), "x"); |
| | | 38 | | |
| | 9 | 39 | | var body = propertyName.Split('.').Aggregate<string?, Expression>(param, (current, member) => Expression.Propert |
| | | 40 | | |
| | 6 | 41 | | var convert = Expression.Convert(body, typeof(object)); |
| | | 42 | | |
| | 6 | 43 | | return Expression.Lambda<Func<T, object?>>(convert, param).Compile(); |
| | | 44 | | } |
| | | 45 | | } |
| | | 46 | | |