Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading