- Home /
C# Distinct ArrayLists
Question: Is there a way to make an arrayList distinct without having to manually search the array list at each insertion? If not is there a better Collection I should use to get the desired effect?
Case: I am adding all the tags of which my main object collides into the array. I only want each to be added once, so I can eventually parse out the amount of objects hit and give point accordingly.
What I am after:
void OnCollisionEnter( Collision collision ){
//Add tag to the arraylist
myArrayList.Add( collision.tag );
//Keep the arraylist distinct //Todo don't call this after each collision.
myArrayList.Distinct(); //Does not exist
}
Unity doesn't seem to think Distinct() exists:
Type `System.Collections.Generic.List' does not contain a definition for `Distinct' and no extension method `Distinct' of type `System.Collections.Generic.List'
**Fixed Have to add: using System.Linq;
Answer by Rabbit-Stew-dio · Nov 13, 2012 at 09:16 PM
If order is not important, use a HashSet. It guarantees that only distinct objects are added to it in the first place.
If you need a specific order, then use a list and make a Contains check before you add the item, or use a list and a HashSet. In the second case, the hashset will be a quick index to test whether you already have the item added.
Example 1: List with contains check:
if (myArrayList.Contains( collision.tag ) == false)
{
myArrayList.Add ( collision.tag );
}
Example 2: Using both a HashSet and a List
HashSet index = new HashSet();
void OnCollisionEnter( Collision collision ){
if (index.Contains(collision.tag))
return;
//Add tag to the arraylist
myArrayList.Add( collision.tag );
index.Add (collision.tag );
}
For a small number of items, the list with the contains check should be sufficiently fast. For a larger number of items (100 or more), the hashset will speed things up for you.
Thanks for the post $$anonymous$$, it was very informative. The Generic List turned out to have exactly what I needed: the Distinct() function. Appreciate your post though.
Answer by Hamilcar-games · Aug 12, 2018 at 12:31 PM
@CostelloNicho using system.linq;
yourlist = yourlist.district().tolist();
Your answer
![](https://koobas.hobune.stream/wayback/20220613083818im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
create a dynamic menu 1 Answer
C# - ArrayList question 2 Answers