List Types

Hi, I’m currently experimenting a bit with AI in a turn based strategy game, and need to make many Lists of Units.
I will be crossing a lot of info within Lists, and Sorting Lists by Unit’s Attributes. (EG: Of List “AvailableUnits”, pick “RangedUnits”, and pick the one with longest range). I have a little experience with ArrayLists, but I would like to know which Type of List would let me make these operations faster and easier.

the key term you’re looking for appears to be “collection”, I googled “c# collection performance” and found pages like:

picking the right collection for what you are doing is highly dependent on how/what you are doing after all

1 Like

A list is generally faster than an array list;

1 Like

Thanks!
Im gonna go with Lists, seems simple enough at the moment!

You’ll also want to look into Linq it will be very handy.
You can do things like this:

Unit pick = units.Where(x => x.available == true).Where(x => x.uType == UnitType.ranged).
                     OrderByDescending(x => x.rangeDist).First();
1 Like

If you can use HashSets over Lists as they’re faster. But remember to override Equal and GetHashCode Methods, or the HashSet cannot work properly with your objects. Also these Lists cannot store duplicate Items. Other than that, they’re one of the fastest options you have.

1 Like

Only if you’re creating new value types. The System.Object implementations work just fine for reference types.

Yeah only needed on newly created classes, forgot to mention that, thanks for adding it :wink:

No - new value types, classes are reference types.

If I create a class, and setup some properties, i usually override Equals and GetHashCode Methods (e.g. a Hero Class might internally compare the level, currentXp, name and what not to get a unique value inside the overridden Equals method, that makes it compareable with other heroes), because lists use the Equals Method to compare the objects. If you do not override it, it simply compares the object itself and not the things you want it to check.

some google result:

Because that’s a fundamental difference between reference types and value types. You’re checking to see if the values contained in the class are the same between two instances. The default behavior is to check if two references are the same instance. It’s the difference between; Do these two Heros have the same values? and Are these two Heros the same hero?

Ultimately it boils down to whether or not you want a set of unique instances or not - which I would imagine, 9 times out of 10 when dealing with reference types, you would.

I was also just calling out your original assertion that a HashSet wouldn’t work properly unless you overrode those methods, which is definitely not true. :slight_smile:

Yeah, that was a good point :wink: