2

I am newbie in unity and use C#, actually i am python developer i try to make a list which can holds only unique Values and if some duplicate value come it will not allow to enter in list

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

list =[2,3,5,7]

**in python we just do this to avoid duplicate in list **

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

But what should we do in C# to achieve very similar results Thanks Your effort will be highly appreciated

Stefan
  • 17,448
  • 11
  • 60
  • 79
Ahmad
  • 61
  • 1
  • 1
  • 9

4 Answers4

8

C# List has similar method: if (!iList.Contains(value)) iList.Add(value);

Alternatively you can use a HashSet<int>. There you don't need to add any conditions:

var hasSet = new HashSet<int>(); 
hashSet.Add(1);
hashSet.Add(1);
starikcetin
  • 1,391
  • 1
  • 16
  • 24
Maxim Goncharuk
  • 1,285
  • 12
  • 20
6

In C# we (can) just do this to avoid duplicate in list:

if (iList.IndexOf(value) == -1 ) {
    iList.Add(value);
}
Stefan
  • 17,448
  • 11
  • 60
  • 79
4

A HashSet would ensure you only have one instance of any object. Or a Dictionary if you want to have a key that is different to the object itself. Again dictionaries do not allow duplicate keys.

A HashSet will not throw an exception if you try to put in a duplicate it just won't add it.

A dictionary will throw a duplicate key exception.

Dave
  • 2,829
  • 3
  • 17
  • 44
3

Consider to build your own type of List that will never add duplicates

public class NoDuplicatesList<T> : List<T>
{
      public override Add(T Item) 
      {
         if (!Contains(item))
                base.Add(item);
      } 
}
Nick Reshetinsky
  • 447
  • 2
  • 13