Ahmad
Ahmad

Reputation: 61

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

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

Upvotes: 2

Views: 13887

Answers (4)

Stefan
Stefan

Reputation: 17658

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

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

Upvotes: 6

Dave
Dave

Reputation: 3017

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.

Upvotes: 4

Maxim Goncharuk
Maxim Goncharuk

Reputation: 1333

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);

Upvotes: 9

Nick Reshetinsky
Nick Reshetinsky

Reputation: 457

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);
      } 
}

Upvotes: 3

Related Questions