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

Ahm*_*mad 1 c# unity-game-engine c#-3.0 c#-4.0 unity5

我是统一的新手并使用C#,实际上我是python开发人员我试图制作一个只能包含唯一值的列表,如果有一些重复值,它将不允许进入列表

List<int> iList = new List<int>();
    iList.Add(2);
    iList.Add(3);
    iList.Add(5);
    iList.Add(7);
Run Code Online (Sandbox Code Playgroud)

list = [2,3,5,7]

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

if(iList.indexof(value)!=-1){
iList.append(value)
}
Run Code Online (Sandbox Code Playgroud)

但是我们应该如何在C#中实现非常相似的结果谢谢您的努力将受到高度赞赏

Max*_*ruk 8

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

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

var hasSet = new HashSet<int>(); 
hashSet.Add(1);
hashSet.Add(1);
Run Code Online (Sandbox Code Playgroud)


Ste*_*fan 6

**在C#中我们(可以)这样做是为了避免重复列表**

if (iList.IndexOf(value) == -1 ) {
    iList.Add(value);
}
Run Code Online (Sandbox Code Playgroud)