.NET Core(C#)中IEqualityComparer
1、IEqualityComparer
IEqualityComparer
是用来比较对象是否相等,需要实现接口的public bool Equals()
和public int GetHashCode()
方法, IEqualityComparer
接口的实现类主要用在Linq.Distinct
方法中。当进行比较的时候,先行运行GetHashCode()
方法比较两个obj的HashCode
(哈希值),如果obj的HashCode
(哈希值)相同,再执行Equals()
方法来比较。如果HashCode
不同,则不执行Equals()
。
2、IEqualityComparer
1) 自定义Box对象添加到字典集合。如果Box对象的尺寸相同,则认为它们相等。
using System;
using System.Collections.Generic;
class Example
{
static void Main()
{
BoxEqualityComparer boxEqC = new BoxEqualityComparer();
var boxes = new Dictionary(boxEqC);
var redBox = new Box(4, 3, 4);
AddBox(boxes, redBox, "red");
var blueBox = new Box(4, 3, 4);
AddBox(boxes, blueBox, "blue");
var greenBox = new Box(3, 4, 3);
AddBox(boxes, greenBox, "green");
Console.WriteLine();
Console.WriteLine("The dictionary contains {0} Box objects.",
boxes.Count);
}
private static void AddBox(Dictionary dict, Box box, String name)
{
try {
dict.Add(box, name);
}
catch (ArgumentException e) {
Console.WriteLine("Unable to add {0}: {1}", box, e.Message);
}
}
}
public class Box
{
public Box(int h, int l, int w)
{
this.Height = h;
this.Length = l;
this.Width = w;
}
public int Height { get; set; }
public int Length { get; set; }
public int Width { get; set; }
public override String ToString()
{
return String.Format("({0}, {1}, {2})", Height, Length, Width);
}
}
class BoxEqualityComparer : IEqualityComparer
{
public bool Equals(Box b1, Box b2)
{
if (b2 == null && b1 == null)
return true;
else if (b1 == null || b2 == null)
return false;
else if(b1.Height == b2.Height && b1.Length == b2.Length
&& b1.Width == b2.Width)
return true;
else
return false;
}
public int GetHashCode(Box bx)
{
int hCode = bx.Height ^ bx.Length ^ bx.Width;
return hCode.GetHashCode();
}
}
输出如下:
Unable to add (4, 3, 4): An item with the same key has already been added.
The dictionary contains 2 Box objects.
相关文档:iequalitycomparer
2) 去除字典中key不同但value是相同对象的重复数据
public class CachedLookup
{
private readonly ConcurrentDictionary _hashSet;
private readonly ConcurrentDictionary> _lookup = new ConcurrentDictionary>();
public CachedLookup(ConcurrentDictionary hashSet)
{
_hashSet = hashSet;
}
public CachedLookup(IEqualityComparer equalityComparer = default)
{
_hashSet = equalityComparer is null ? new ConcurrentDictionary() : new ConcurrentDictionary(equalityComparer);
}
public List Get(TKey key) => _lookup.ContainsKey(key) ? _lookup[key] : null;
public List Get(TKey key, Func> getData)
{
if (_lookup.ContainsKey(key))
return _lookup[key];
var result = DedupeAndCache(getData(key));
_lookup.TryAdd(key, result);
return result;
}
public async ValueTask> GetAsync(TKey key, Func>> getData)
{
if (_lookup.ContainsKey(key))
return _lookup[key];
var result = DedupeAndCache(await getData(key));
_lookup.TryAdd(key, result);
return result;
}
public void Add(T value) => _hashSet.TryAdd(value, value);
public List AddOrUpdate(TKey key, List data)
{
var deduped = DedupeAndCache(data);
_lookup.AddOrUpdate(key, deduped, (k,l)=>deduped);
return deduped;
}
private List DedupeAndCache(IEnumerable input) => input.Select(v => _hashSet.GetOrAdd(v,v)).ToList();
}
使用示例:
public class ExampleUsage
{
private readonly CachedLookup _lookup
= new CachedLookup(new LanguageInfoModelComparer());
public ValueTask> GetLanguagesAsync(string frontendId, string languageId, string accessId)
{
return _lookup.GetAsync((frontendId, languageId, accessId), GetLanguagesFromDB(k));
}
private async Task> GetLanguagesFromDB((string frontendId, string languageId, string accessId) key) => throw new NotImplementedException();
}
public class LanguageInfoModel
{
public string FrontendId { get; set; }
public string LanguageId { get; set; }
public string AccessId { get; set; }
public string SomeOtherUniqueValue { get; set; }
}
public class LanguageInfoModelComparer : IEqualityComparer
{
public bool Equals(LanguageInfoModel x, LanguageInfoModel y)
{
return (x?.FrontendId, x?.AccessId, x?.LanguageId, x?.SomeOtherUniqueValue)
.Equals((y?.FrontendId, y?.AccessId, y?.LanguageId, y?.SomeOtherUniqueValue));
}
public int GetHashCode(LanguageInfoModel obj) =>
(obj.FrontendId, obj.LanguageId, obj.AccessId, obj.SomeOtherUniqueValue).GetHashCode();
}
相关文档:system.object.gethashcode