Skip to content

Instantly share code, notes, and snippets.

@AndrewAllison
Last active December 20, 2015 02:09
Show Gist options
  • Save AndrewAllison/6053964 to your computer and use it in GitHub Desktop.
Save AndrewAllison/6053964 to your computer and use it in GitHub Desktop.
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));
}
}
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);
}
}
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