【问题标题】:Unique collection set [duplicate]独特的收藏集[重复]
【发布时间】:2021-11-16 04:36:45
【问题描述】:

是否存在类似于表的集合类型,但表中的每一行/集合都是唯一的,类似于数据库unique 约束?

| "txt" | "data"  |
| "txt" | "txt"   |
| "txt" | "data"  | // Duplicate row
| "data"| "txt"   | // Duplicate row
| "exe" | "path"  |
| "exe" | "path2" |
| "exe" | "path"  | // Duplicate row

【问题讨论】:

  • HashSet<(string s1, string s2)>?
  • 如果你创建一个类,你可以通过实现IEquatable和覆盖GetHashCode来使用HashSet
  • @41686d6564 awe cool 没想到元组。
  • @41686d6564 项目的顺序是否重要,例如txt,datadata,txt 是否相同?
  • @GetOffMyLawn 似乎很简单,您可以进行测试。如果这对您不起作用,您可以随时创建自定义 IEquatable,就像 Steven 提到的那样。

标签: c#


【解决方案1】:

在 cmets 上进行扩展,如果您希望该行用作聚合哈希而不是仅用作键,您可能需要创建自定义 IEqualityComparer<(string, string)> 并将其传递给 HashSet。

public class ValueTupleEqualityComparer : IEqualityComparer<(string s1, string s2)>
{
    public bool Equals((string s1, string s2) other)
    {
        return base.Equals(other);
    }

    public bool Equals((string s1, string s2) x, (string s1, string s2) y)
    {
        if (object.ReferenceEquals(x, y))
            return true;

        if (x.s1 == y.s1 && x.s2 == y.s2)
            return true;

        if (x.s1 == y.s2 && x.s2 == y.s1)
            return true;

        return false;
    }

    public int GetHashCode((string s1, string s2) obj)
    {
        return base.GetHashCode();
    }
}

在针对您的数据集进行测试时:

var hashSet = new HashSet<(string s1, string s2)>(new ValueTupleEqualityComparer());

hashSet.Add(("txt", "data"));
hashSet.Add(("txt", "txt"));
hashSet.Add(("txt", "data"));
hashSet.Add(("data", "txt"));
hashSet.Add(("exe", "path"));
hashSet.Add(("exe", "path2"));
hashSet.Add(("exe", "path"));

输出如下结果:

txt data 
txt txt 
exe path 
exe path2 

这会在使用“column1”和“column2”的情况下为您提供独特的结果,无论顺序如何。

【讨论】:

    【解决方案2】:

    如果您只关心一列,您可以使用Dictionary,其中键必须是唯一的;否则,您可以使用HashSet

    注意

    HashSet 集合未排序且不能包含重复元素。如果对于您的应用程序而言,顺序或元素重复比性能更重要,请考虑将 List 类与 Sort 方法一起使用。

    就个人而言,我发现Dictionary 非常有用,因为它阅读速度非常快。此外,还有一个线程安全的ConcurrentDictionary,可以在使用线程时节省大量时间和调试。

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      相关资源
      最近更新 更多