Bruno Brant
Bruno Brant

Reputation: 8564

Is the order of elements on a C# List<T> deterministic?

I've always thought otherwise, but recently I had the need to know:

If I add elements to a list in a certain order, am I guaranteed to find then always on the same order?

Thanks!

Upvotes: 15

Views: 5584

Answers (3)

OJ.
OJ.

Reputation: 29399

Yes, it is deterministic. Bear in mind that if you want to use List<T> across threads then, as with anything, you can't guarantee the order in which the interactions would happen.

Upvotes: 8

KeithS
KeithS

Reputation: 71593

Yes. List is an indexed collection; using Add() to put elements into the List will cause them to be indexed in the order they're added.

Upvotes: 3

Tim Robinson
Tim Robinson

Reputation: 54764

Yes; you control the ordering of a List<T>.

You can assume that any .NET collection with a list[int] indexer has a predictable ordering; otherwise, the numerical index wouldn't make any sense. By comparison, it's not possible to use a numerical index with a Dictionary<K,V>, and when you enumerate a dictionary, the ordering isn't guaranteed.

Upvotes: 33

Related Questions