如何避免列表中的重复值统一使用 C#

How to avoid duplicate value in list Using C# in unity

我是 unity 新手,使用 C#,实际上我是 python 开发人员,我尝试制作一个列表,该列表只能包含唯一值,如果出现重复值,它将不允许进入列表

List<int> iList = new List<int>();
    iList.Add(2);
    iList.Add(3);
    iList.Add(5);
    iList.Add(7);

列表=[2,3,5,7]

**在 python 中,我们这样做只是为了避免在列表中出现重复 **

if(iList.indexof(value)!=-1){
iList.append(value)
}

但是我们应该在 C# 中做什么才能获得非常相似的结果谢谢 我们将不胜感激您的努力

C# List 有类似的方法: if (!iList.Contains(value)) iList.Add(value);

或者您可以使用 HashSet<int>。那里你不需要添加任何条件:

var hasSet = new HashSet<int>(); 
hashSet.Add(1);
hashSet.Add(1);

HashSet 将确保您只有一个对象的实例。或者字典,如果你想拥有一个与对象本身不同的键。同样,字典不允许重复键。

如果您尝试放入副本,HashSet 不会抛出异常,它只是不会添加。

字典会抛出重复键异常。

考虑构建您自己的 List 类型,它永远不会添加重复项

public class NoDuplicatesList<T> : List<T>
{
      public override Add(T Item) 
      {
         if (!Contains(item))
                base.Add(item);
      } 
}

**在 C# 中,我们(可以)这样做以避免列表中出现重复**

if (iList.IndexOf(value) == -1 ) {
    iList.Add(value);
}