Last active
December 20, 2015 02:09
-
-
Save AndrewAllison/6053964 to your computer and use it in GitHub Desktop.
A nice way of doing Except and Distinct: Original credit goes to:
http://brendan.enrick.com/post/linq-your-collections-with-iequalitycomparer-and-lambda-expressions.aspx
http://www.joe-stevens.com/2010/08/17/linq-lambda-expression-iequalitycomparer-for-ienumerable-distinct-and-except/
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
public static class EnumerableExtensions | |
{ | |
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> enumerable, Func<TSource, TSource, bool> comparer) | |
{ | |
return enumerable.Distinct(new LambdaComparer<TSource>(comparer)); | |
} | |
public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TSource, bool> comparer) | |
{ | |
return first.Except(second, new LambdaComparer<TSource>(comparer)); | |
} | |
} |
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
public class LambdaComparer<T> : IEqualityComparer<T> | |
{ | |
private readonly Func<T, T, bool> _lambdaComparer; | |
private readonly Func<T, int> _lambdaHash; | |
public LambdaComparer(Func<T, T, bool> lambdaComparer) : | |
this(lambdaComparer, o => 0) | |
{ | |
} | |
public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash) | |
{ | |
if (lambdaComparer == null) | |
throw new ArgumentNullException("lambdaComparer"); | |
if (lambdaHash == null) | |
throw new ArgumentNullException("lambdaHash"); | |
_lambdaComparer = lambdaComparer; | |
_lambdaHash = lambdaHash; | |
} | |
public bool Equals(T x, T y) | |
{ | |
return _lambdaComparer(x, y); | |
} | |
public int GetHashCode(T obj) | |
{ | |
return _lambdaHash(obj); | |
} | |
} |
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
List<Role> usersRoles = user.Roles.ToList(); | |
List<Role> roles = new TestDbContext().Roles.ToList(); | |
IEnumerable<Role> rolesUserIsNotIn = roles.Except(usersRoles, (role, role1) => role.Id == role1.Id); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment