I’ll do my best to explain what I’m doing here – I have used this approach a few times but have never felt that good about it. I am sure there must be a better way of doing it, please enlighten me.
class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(MyObject))
{
return false;
}
return ((MyObject)obj).Id == Id;
}
public override int GetHashCode()
{
return Id;
}
}
[Test]
public void Blah()
{
IDictionary<object, MyObject> duplicateMergerDict = new Dictionary<object, MyObject>();
MyObject dup1 = new MyObject { Id = 0, Name = "Smith" };
MyObject dup2 = new MyObject { Id = 0, Name = "Collins" };
MyObject nonDup = new MyObject { Id = 1, Name = "Smith" };
IEnumerable<MyObject> test =
new[] { dup1, dup2, nonDup };
foreach (var myObject in test)
{
MyObject existing;
if (duplicateMergerDict.TryGetValue(myObject, out existing))
{
existing.Name = string.Format("{0} {1}", existing.Name, myObject.Name);
}
else
{
duplicateMergerDict.Add(myObject, myObject);
}
}
Assert.That(duplicateMergerDict.Count, Is.EqualTo(2));
Assert.That(duplicateMergerDict[dup1], Is.SameAs(dup1));
Assert.That(duplicateMergerDict[dup2], Is.SameAs(dup1));
Assert.That(dup1.Name, Is.EqualTo("Smith Collins"));
Assert.That(duplicateMergerDict[nonDup], Is.SameAs(nonDup));
}
Basically I want to accumulate duplicate entries using GetHashCode and Equals overriding. (Or should I use a composite key object – even for much more complex cases than this?). The method above seems messy but perhaps it’s the best way?
Can someone wiser than me please show me where I can improve on this?
Thanks.
You can’t. That’s not what they’re there for. They are solely present to find a key, testing it for equality. You certainly shouldn’t be mutating anything in there.
Your approach using
TryGetValueworks, but it requires that your values are mutable, which isn’t pleasant IMO. You might want to look atConcurrentDictionary<,>though, which has a handyAddOrUpdatemethod which sounds like it does exactly what you want.