List vs Dictionary .NET Collection Types

List vs Dictionary Collection Types Page Banner Image

Introduction

In .NET, list and dictionary are useful collection types. They are easy accessibility and convenient to use. There are advantages to using these types over an array or hash tables. There are also a lot of different variations and even concurrent versions but for now, we will cover the most basic types. Next, we’ll start with the list collection.

#Analysis TypeListDictionary
1Item Search SpeedO(N)O(1)
2Index SpeedO(1)O(1)
3Initial SizeYesYes
4Automatic ResizeO(1)O(1)
5Size PropertyCount()Count()
6AddO(N)(If expansion is required)O(N)(If expansion is required)
7InsertO(N)(If expansion is required)none
8DeleteO(N)O(1)
9DuplicatesYesKeys:No | Values:Yes

LIST Description

Example Syntax
List<int> list = new List<int>(3);//Initial size of 3

Uses – Use this when you need a quick collection type to use or you need a collection to loop through that will not be too big. If you’re not sure which collection type to use when starting a List is a good place to start. There are other list-type structures similar to the list.

List Pros

A simpler structure to use than a dictionary. If you just looping through a collection then this is a great choice. The underlying structure is an expanding and contracting array. The array expands automatically so you don’t have to write any extra code. The indexing is fast with a runtime of O(1) and the loop speed is slightly faster than looping through a dictionary. You can have duplicate values in a list. As you can see below example that a value can be extracted by the index “[]” operator which provides the address. The address starts at 0,1,2,3..etc, so if there are 7 items in a list then each element address would start at 0 and then go to 6. When using the index operator you must provide a valid address. If you try to access an index that is not in the list then an exception is thrown. See below for the code example.

static void Main(string[] args)
{
    List<string> carList = new List<string>();
    carList.Add("Honda CRV");
    carList.Add("Toyota Camry");
    carList.Add("Toyota Corolla");
    carList.Add("Hyundai Sonata");
    carList.Add("Ford F1");
    carList.Add("Ford Fusion");
    carList.Add("Telsa Model 3");
    Console.WriteLine($"Car:{GetListData(3, carList)}, from index:{3}");
    Console.WriteLine($"Car:{GetListData(5, carList)}, from index:{5}");
    Console.WriteLine($"Car:{GetListData(1, carList)}, from index:{1}");
    Console.WriteLine($"Car:{GetListData(10, carList)}, from index:{10}");
}
public static string GetListData(int index, List<string> list)
{
    if (list.Count > index)
    {
        return list[index];
    }
    return "";
}

Console Output

Car:Hyundai Sonata, from index:3
Car:Ford Fusion, from index:5
Car:Toyota Camry, from index:1
Car:, from index:10 // not found in the list

List Cons

When inserting into any index other than the last element the array is copied and moved to make room for the new entry so it can be a more expensive operation when the list grows really big. Searching through a list for an item can be time-consuming if the list is very large. Also, be careful about the index value you provide, and make sure it can be found in the list. Write code to insure the index exists in the list or else you might hit an exception.

Dictionary Description

Dictionary<string,string> dictionary = new Dictionary<string,string>(5);//Initial size of 5

Uses – I usually use this when there is a key-value pair or something that I may search for later. Or when there’s a value that’s associated with another value or object. Usually, the collection tends to be large and keys are required to be unique and can be any object.

Example uses – If I have a Dictionary that has a car name string as the key and then the value as the object of car data. If the user selects a car name. Instead of looping through a list to find the information. If I have a dictionary then I use the car name as the key and then instantly get the data associated with that key. See the sample code below.

static void Main(string[] args)
{
    Dictionary<string, Car> dictionary = new Dictionary<string, Car>();
    dictionary.Add("Honda CRV", new Car("Honda CRV", "Blue", "SUV Crossover"));
    dictionary.Add("Toyota Camry", new Car("Toyota Camry", "Red", "Sedan"));
    dictionary.Add("Toyota Corolla", new Car("Toyota Corolla", "White", "Sedan"));
    dictionary.Add("Hyundai Sonata", new Car("Hyundai Sonata", "Gray", "Sedan"));
    dictionary.Add("Ford F1", new Car("Ford F1", "Dark Gray", "Truck"));
    dictionary.Add("Ford Fusion", new Car("Ford Fusion", "Sky Blue", "Sedan"));
    dictionary.Add("Telsa Model 3", new Car("Telsa Model 3", "Dark Green", "Sedan"));
    Console.WriteLine(GetDictionaryData("Honda CRV", dictionary));
    Console.WriteLine(GetDictionaryData("Telsa Model 3", dictionary));
    Console.WriteLine(GetDictionaryData("Ford F1", dictionary));
    Console.WriteLine(GetDictionaryData("Toyota Camry", dictionary));
    Console.WriteLine(GetDictionaryData("Audi A3", dictionary));
}
public static Car GetDictionaryData(string key, Dictionary<string, Car> dictionary)
{
    if (dictionary.ContainsKey(key))
    {
        return dictionary[key];
    }
    return new Car();
}
public class Car
{
    public string Name { get; set; }
    public string Color { get; set; }
    public string Type { get; set; }
    public Car(string name, string color, string type)
    {
        Name = name;
        Color = color;
        Type = type;
    }
    public Car()
    {
    }
    public override string ToString()
    {
        return $"Name:{Name}, Color:{Color}, Type:{Type}";
    }
}

Console Output

Name:Honda CRV, Color:Blue, Type:SUV Crossover
Name:Telsa Model 3, Color:Dark Green, Type:Sedan
Name:Ford F1, Color:Dark Gray, Type:Truck
Name:Toyota Camry, Color:Red, Type:Sedan
Name:, Color:, Type: //When key not found in the dictionary

Dictionary Pros

Fast value look-up by the key with an O(1) constant lookup time. Key value pairs make it a great structure for search. If you know which key needs. You can loop through dictionary keys or their values

Dictionary Cons

You need to know the key ahead of time or else you end up just looping through the structure and then you may be better off with a list. Check out best practices to avoid these pitfalls. You need to write code to check to see if the key exists in the dictionary. If you try to access a key that is not found in the dictionary then an exception is thrown so check every time you try to access the dictionary if the key is there. Keys have to be unique

Examples Of Problems And Preference Of Collections

Reading database entries that have a unique index value and associated values. The index will be used later to find the values. I would use a dictionary for this because there is a unique index that I can use as a key. Gather all the values of a type and display them in a drop-down list on the UI. I would use a list of this since I’m just gathering the values and displaying them on the UI. I would use a List A collection of different soda inventory and the count of each type of soda. I would use a Dictionary string, int so that the keys can be the type of soda and the values are the count of each soda. Display the data on the top 10 laptops and specs from the database. I would use a list of this. I would have an object that holds all the data of the specs and query the database to get the top laptops and their specs from the database. You need to search through a large collection of grocery store items. The UI searches by the exact name of the item. If the item is not in stock then show the item not found. If the item is in stock then show all information related to the item. I would use a dictionary for this. The item name would the be key and the associated information would be in an object. If the name is not found in the dictionary then the item would be considered not in stock.

C# Programming for Unity Game Development Specialization

COURSERA

C# Programming for Unity Game Development Specialization

4.7 (2,230 reviews)

Beginner level

No previous experience is necessary

3-months at 10 hours a week (At your pace)

$59 / month or audit, and financial aid available

If you want to learn more about C# then check out this course on Coursera. It's a 3 month course to take you through the basics of C#.

You can get started with programming using C# and apply it to Unity games in this beginner-level program. Facilitated by the University of Colorado, the program offers a chance to grasp the basics of C# and utilize the knowledge to develop Unity games.

[Full Disclosure: As an affiliate, I receive compensation if you purchase through this link]

Start Your 7-day Free Trial
Get Latest Updates
Comments Section