So this is the code that I have tried, but it adds the same object more than once:
namespace TestComparison
{
public interface IAddable
{
int RandomIntValue { get; set; } // often Times this value will repeat.
}
public class AdditionManager<T> where T : IAddable
{
private List<T> addables;
public AdditionManager()
{
addables = new List<T>();
}
public void Add(T _addable)
{
if (!addables.Contains(_addable))
{
addables.Add(_addable);
}
}
}
public class TestAddable : IAddable
{
public int RandomIntValue { get; set; }
public Data UniqueData = new Data() { UniqueId = 10023 }; // This is what really make each item unique
}
public class Data
{
public int UniqueId { get; set; }
}
}
I've heard about the IEqualityComparer and I have implemented it in non-generic classes, but I'm not quite sure how to implement it here.
You can use dependency injection to provide you with generic implementation. Doing so you'll need to provide the custom
IEqualityComparer<T>implementation that you want at the point of generic object's construction.However, if you are looking for you list of
addablesto be unique based on some constraint, I would not use the above implementation for performance reasons. As theList<T>.Containscheck will become slower as the list grows larger.If the order of the list does not matter change your
List<T>to aHashSet<T>.HashSet<T>.Containswill be just as quick as aDictionary<TKey, TValue>lookup. But this call can be avoided altogether withHashSet<T>as theAddcall will first check to see if the item is in the set before adding it, and returntrueorfalseto indicate it was added or not`So if the order of
addablesis of not concern, then I would use the following implementation.If you need to maintain the order of
addablesthen I suggest maintaining the list of objects in both aHashSet<T>andList<T>. This will provide you with the performance of the above implementation, but maintain the addition order on your items. In this implementation any of the operations you need to perform, do them against theList<T>and only use theHashSet<T>to make sure the item isn't already present when adding toList<T>If you are going to have some type ofRemoveoperation, make sure to remove the item from both theHashSet<T>andList<T>To create this object using
TestAddableyou'll need anIEqualityComparer<TestAddable>like the following. As others have suggested, the field(s) you are doing your comparison on should be made immutable, as a mutable key is going to cause bugs.Then to create the manager object do: