Created
January 26, 2022 07:01
-
-
Save kudchikarsk/c709218cce123878564a5f287f74c299 to your computer and use it in GitHub Desktop.
IEnumerableExtension.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
namespace Aasani.CRM.Logic | |
{ | |
public static class IEnumerableExtension | |
{ | |
public static IEnumerable<T> OrderByName<T>(this IEnumerable<T> @this, string propName) | |
{ | |
ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "contact"); | |
MemberExpression propertAccessExpression = Expression.Property(parameterExpression, propName); | |
var query = Expression.Lambda(propertAccessExpression, parameterExpression).Compile(); | |
var methods = typeof(Enumerable).GetMethods(); | |
var orderByMethod = methods.First(m => m.Name == "OrderBy" && m.GetParameters().Length == 2); | |
var genericOrderByMethod = orderByMethod.MakeGenericMethod(new[] { typeof(T), propertAccessExpression.Type }); | |
return (IEnumerable<T>) | |
genericOrderByMethod.Invoke(null, new object[] { @this, query }); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment