Last active
May 15, 2018 10:09
-
-
Save mshwf/c7e6a6adf63b918bd73dc1c1bba749b4 to your computer and use it in GitHub Desktop.
This file contains 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
public static IQueryable<T> SelectExcept<T, TKey>(this IQueryable<T> sequence, | |
Expression<Func<T, TKey>> excluder) where T : new() | |
{ | |
List<string> excludedProperties = new List<string>(); | |
if (excluder.Body is MemberExpression memberExpression) | |
{ | |
excludedProperties.Add(memberExpression.Member.Name); | |
} | |
else if (excluder.Body is NewExpression anonymousExpression) | |
{ | |
excludedProperties.AddRange(anonymousExpression.Members.Select(m => m.Name)); | |
} | |
var includedProperties = typeof(T).GetProperties() | |
.Where(p => !excludedProperties.Contains(p.Name)); | |
return sequence.Select(x => Selector(x, includedProperties)); | |
} | |
private static T Selector<T>(T obj, IEnumerable<PropertyInfo> properties) | |
{ | |
var instance = Activator.CreateInstance<T>(); | |
foreach (var property in properties) | |
property.SetValue(instance, property.GetValue(obj), null); | |
return instance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment