如何在保存到数据库之前维护唯一列表? - C#

发布于 2024-10-02 14:33:22 字数 689 浏览 2 评论 0原文

一个简化的场景:

  • 我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

凶凌 2024-10-09 14:33:22

您可以使用 HashSet

哈希集是唯一的、无序的集合。
添加一个已经存在的元素将不会执行任何操作。 (并返回 false

请注意,您必须覆盖 FooEquals 和 GetHashCode > 按值比较的类。

另请注意,哈希集本质上是无序的;如果您关心插入顺序,则无法使用它。


或者,您可以使用 LINQ 检查您的列表是否有重复项:

if (!foos.Any(f => f.Description == txtOne.Text))
    foos.Add(new Foo { Description = txtOne.Text, IsFoo = true });

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 and GetHashCode on the Foo 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:

if (!foos.Any(f => f.Description == txtOne.Text))
    foos.Add(new Foo { Description = txtOne.Text, IsFoo = true });
菊凝晚露 2024-10-09 14:33:22

要扩展 SLAks 的答案,您可以执行以下操作:

public class FooComparer : IEqualityComparer<Foo> {
    public static readonly FooComparer Instance = new FooComparer();

    private FooComparer() { }

    public bool Equals(Foo a, Foo b) {
        if (a == null)
            return b == null;

        if (b == null)
            return false;

        // For case-sensitivity:
        return a.Description == b.Description;

        // For case-insensitivity:
        return String.Equals(a.Description, b.Description, StringComparison.OrdinalIgnoreCase);
    }

    public int GetHashCode(Foo obj) {
        // For case-sensitivity:
        return obj.Description.GetHashCode();

        // For case-insensitivity:
        return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Description);
    }
}

然后将您的项目存储在 HashSet 中,如下所示:

var hashSet = new HashSet<Foo>(FooComparer.Instance);
hashSet.Add(new Foo() { ... });

使用此代码,如果有第二个 Foo 对象如果被添加到哈希集中并且与哈希集中已有的描述相同,则不会添加新对象。

To expand on SLaks' answer, you could do something like this:

public class FooComparer : IEqualityComparer<Foo> {
    public static readonly FooComparer Instance = new FooComparer();

    private FooComparer() { }

    public bool Equals(Foo a, Foo b) {
        if (a == null)
            return b == null;

        if (b == null)
            return false;

        // For case-sensitivity:
        return a.Description == b.Description;

        // For case-insensitivity:
        return String.Equals(a.Description, b.Description, StringComparison.OrdinalIgnoreCase);
    }

    public int GetHashCode(Foo obj) {
        // For case-sensitivity:
        return obj.Description.GetHashCode();

        // For case-insensitivity:
        return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Description);
    }
}

Then store your items in a HashSet<Foo> like so:

var hashSet = new HashSet<Foo>(FooComparer.Instance);
hashSet.Add(new Foo() { ... });

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.

终遇你 2024-10-09 14:33:22

可以在 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....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文