A simplified scenario:
- I have a
List<Foo>. Foohas two properties Description (string), IsFoo (bool)
E.g:
var foos = new List<Foo>();
User can “add new Foo’s” via textboxes, then on form submit i do this:
foos.Add(new Foo { Description = txtOne.Text, IsFoo = true });
foos.SaveToDb();
However, there are multiple textboxes, and if for example they type “FooBar” in textbox one, then “FooBar” in textbox two, i do not want to show an error, but i simply do not want to add them to the collection. (don’t worry about the reason behind this, this is a simplified scenario).
I don’t need to show anything to the UI, just when they submit the form, before persisting to the database i need to remove any duplicates (or prevent them from being added to the list in the first place).
What’s the easiest/best way to do this? Dictionary perhaps?
I’m using C#4, LINQ, .NET 4.
You can use a
HashSet<Foo>.HashSets are unique, unordered collections.
Adding an element that already exists will silently do nothing. (and return
false)Note that you must override
EqualsandGetHashCodeon theFooclass to compare by value.Also note that hashsets are intrinsically unordered; if you care about insertion order, you can’t use it.
Alternatively, you can use LINQ to check whether your list has a duplicate: