-
Notifications
You must be signed in to change notification settings - Fork 0
/
MappedEqualityComparer.cs
49 lines (44 loc) · 1.53 KB
/
MappedEqualityComparer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
namespace Recore.Collections.Generic
{
/// <summary>
/// Compares instances of a type based on the output of a mapping function.
/// </summary>
public sealed class MappedEqualityComparer<T, TMapped> : IEqualityComparer<T?>
{
private readonly static EqualityComparer<TMapped> mappingComparer = EqualityComparer<TMapped>.Default;
private readonly Func<T, TMapped> mapping;
/// <summary>
/// Creates an instance of <see cref="MappedEqualityComparer{T, TMapped}"/>.
/// </summary>
public MappedEqualityComparer(Func<T, TMapped> mapping)
{
this.mapping = mapping ?? throw new ArgumentNullException(nameof(mapping));
}
/// <summary>
/// Invokes the mapping function on two objects and checks if the outputs are equal.
/// </summary>
public bool Equals(T? x, T? y)
{
TMapped? mappedX = x == null ? default(TMapped?) : mapping(x);
TMapped? mappedY = y == null ? default(TMapped?) : mapping(y);
return mappingComparer.Equals(mappedX, mappedY);
}
/// <summary>
/// Hashes the mapped output of an object.
/// </summary>
public int GetHashCode(T obj)
{
var mapped = mapping(obj);
if (mapped == null)
{
return 0;
}
else
{
return mappingComparer.GetHashCode(mapped);
}
}
}
}