gpt4 book ai didi

c# - .NET 中只允许唯一项的集合?

转载 作者:IT王子 更新时间:2023-10-29 03:36:18 29 4
gpt4 key购买 nike

C# 中是否有一个集合不允许您向其中添加重复项?例如,愚蠢的类

public class Customer {
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }

public override int GetHashCode() {
return (FirstName + LastName + Address).GetHashCode();
}

public override bool Equals(object obj) {
Customer C = obj as Customer;
return C != null && String.Equals(this.FirstName, C.FirstName) && String.Equals(this.LastName, C.LastName) && String.Equals(this.Address, C.Address);
}
}

下面的代码(显然)会抛出一个异常:

Customer Adam = new Customer { Address = "A", FirstName = "Adam", LastName = "" };
Customer AdamDup = new Customer { Address = "A", FirstName = "Adam", LastName = "" };

Dictionary<Customer, bool> CustomerHash = new Dictionary<Customer, bool>();
CustomerHash.Add(Adam, true);
CustomerHash.Add(AdamDup, true);

但是是否有一个类可以类似地保证唯一性,但没有 KeyValuePairs?我以为HashSet<T>会那样做,但阅读文档后,类似乎只是一个集合实现(看图)。

最佳答案

HashSet<T>是你要找的。来自 MSDN (强调):

The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

请注意 HashSet<T>.Add(T item) method返回 bool -- true如果该项目已添加到集合中; false如果该项目已经存在。

关于c# - .NET 中只允许唯一项的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5157787/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com