C# – Unique List Collection
Ever wonder how you can create a unique list based on the certain criteria you’ve specified? See code below
////// Unique Collection /// ///public class UniqueCollection : List { public UniqueCollection() { } /// /// Method that adds a new item if item is unique based on specified condition /// /// /// ///Returns true if item is added to the collection public bool AddUniqueValue(T item, PredicateuniqueCheckCondition) { bool isAdded = true; foreach(T i in this) { if (uniqueCheckCondition(i)) { isAdded = false; break; } } if (isAdded) { this.Add(item); } return isAdded; } }
Sample use:
Guid dupGuid = Guid.NewGuid(); TestClass item1 = new TestClass { GUID = dupGuid.ToString() , SettingReference = "Test" }; TestClass item2 = new TestClass { GUID = dupGuid.ToString(), SettingReference = "Test" }; UniqueCollectiontarget = new UniqueCollection (); target.AddUniqueValue(item1, i => i.GUID == item1.GUID); target.AddUniqueValue(item2, i => i.GUID == item2.GUID); Assert.AreEqual(1, target.Count);