Home > Mobile >  What is the difference between an Ordered and Unordered Collection in .NET
What is the difference between an Ordered and Unordered Collection in .NET

Time:11-28

I have been learning about collection in .NET, and I have come across the terms, Ordered and Unordered. I do not know what the difference is between them. Could someone please explain what exactly is the difference, and when one is preferred over the other.

CodePudding user response:

In mathematical terms, an ordered collection is like a sequence, an unordered collection is like a set.

In practical terms, you use an ordered collection if, well... order matters, and an unordered collection if it doesn't.

As a concrete example:

  • I want to store which file extensions are fine for my file uploading service. I'd use an unordered collection, since I only care whether an entry is in the collection or not. I don't care about the order.

    var imageExtensions = new HashSet<string>() { "gif", "jpg", "png" };
    
    // I might just as well have written { "jpg", "png", "gif" } -- it doesn't matter
    
  • I want to store the words of a sentence. The sentence might have duplicate words, and I might want to refer to the "third" word by index number. Here, I use an ordered collection.

    var words = new List<string>() { "one", "small", "step", "for", "man", "one", "giant", "leap", "for", "mankind" };
    

In the .NET base class library, unordered collections are usually optimized for efficiently finding elements of the collection. For example, HashSet<T>.Contains is an O(1) operation. On the other hand, finding an element in a List<T> requires traversing the list and is, thus, an O(n) operation.

  • Related