.net - How to maintain unique List Before Saving To Database? - C# -
a simplified scenario:
- i have
list<foo>
. foo
has 2 properties description (string), isfoo (bool)
e.g:
var foos = new list<foo>();
user can "add new foo's" via textboxes, on form submit this:
foos.add(new foo { description = txtone.text, isfoo = true }); foos.savetodb();
however, there multiple textboxes, , if example type "foobar" in textbox one, "foobar" in textbox two, do not want show error, not want add them collection. (don't worry reason behind this, simplified scenario).
i don't need show ui, when submit form, before persisting database need remove duplicates (or prevent them being added list in first place).
what's easiest/best way this? dictionary perhaps?
i'm using c#4, linq, .net 4.
you can use hashset<foo>
.
hashsets unique, unordered collections.
adding element exists silently nothing. (and return false
)
note must override equals
, gethashcode
on foo
class compare value.
also note hashsets intrinsically unordered; if care insertion order, can't use it.
alternatively, can use linq check whether list has duplicate:
if (!foos.any(f => f.description == txtone.text)) foos.add(new foo { description = txtone.text, isfoo = true });
Comments
Post a Comment