如何在保存到数据库之前维护唯一列表? - C#
一个简化的场景:
- 我有一个
List
。 Foo
有两个属性 Description (string)、IsFoo (bool)
例如:
var foos = new List<Foo>();
用户可以通过文本框“添加新的 Foo”,然后在表单提交时我这样做:
foos.Add(new Foo { Description = txtOne.Text, IsFoo = true });
foos.SaveToDb();
但是,有多个文本框,例如,如果他们在文本框第一个中键入“FooBar”,则在文本框中键入“FooBar”文本框二,我不想显示错误,但我只是不想将它们添加到集合中。 (不用担心这背后的原因,这是一个简化的场景)。
我不需要向用户界面显示任何内容,只是当他们提交表单时,在保存到数据库之前,我需要删除任何重复项(或首先阻止它们添加到列表中)。
最简单/最好的方法是什么?也许是字典?
我正在使用 C#4、LINQ、.NET 4。
A simplified scenario:
- I have a
List<Foo>
. Foo
has 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
HashSet
。哈希集是唯一的、无序的集合。
添加一个已经存在的元素将不会执行任何操作。 (并返回
false
)请注意,您必须覆盖
Foo
Equals 和GetHashCode
> 按值比较的类。另请注意,哈希集本质上是无序的;如果您关心插入顺序,则无法使用它。
或者,您可以使用 LINQ 检查您的列表是否有重复项:
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
Equals
andGetHashCode
on theFoo
class 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:
要扩展 SLAks 的答案,您可以执行以下操作:
然后将您的项目存储在
HashSet
中,如下所示:使用此代码,如果有第二个
Foo
对象如果被添加到哈希集中并且与哈希集中已有的描述相同,则不会添加新对象。To expand on SLaks' answer, you could do something like this:
Then store your items in a
HashSet<Foo>
like so:With this code, if a second
Foo
object is added to the hashset and has an identical description as one already present in the hashset, the new object will simply not be added.可以在 linq 中使用 Distinct 吗?
这是VB(并不准确,因为我在这台机器上没有VS),但大致如下:
Dim ie as IEnumerable(of Foo) = From obj As Foo In Foo's Select obj Distinct
thenimplent IEqualityComparer? - 看起来@cdhowie 刚刚回答了......
Can you use Distinct in linq?
This is VB (and not accurate as I've not got VS on this machine), but something along the lines of:
Dim ie as IEnumerable(of Foo) = From obj As Foo In Foo's Select obj Distinct
Then implent IEqualityComparer? - lookd like @cdhowie just answered....