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

前端 未结 3 1119
[愿得一人]
[愿得一人] 2021-01-17 15:10

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

相关标签:
3条回答
  • 2021-01-17 15:37

    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.

    0 讨论(0)
  • 2021-01-17 15:47

    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.

    0 讨论(0)
  • 2021-01-17 15:51

    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.

    0 讨论(0)
提交回复
热议问题