DEV Community

Cover image for When use Array, List, and Dictionaries in .NET
Dany Paredes
Dany Paredes

Posted on • Edited on

When use Array, List, and Dictionaries in .NET

The Array, Lists and Dictionaries are the most basic collections in .NET and everyone has his scenery to be used, I will explain a bit about each one, for the examples I created the class Team to show the examples.

public class Team
{
    public int Id { get; set; }
    public string Initials { get; set; }
    public string Name { get; set; }
    public int Position { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Array

The Array is a data type used for store data the same type, fixed-size and needs to be in order. The Array requires the type and the size, the type in my example is Team but can be int, string... etc.

Team[] NbaTeams = new Team[3];
Enter fullscreen mode Exit fullscreen mode

To add elements into the array, use the index to set the value into the array.

Team[] nbaTeams = new Team[3];
nbaTeams[0] = new Team() {Id = 1, Initials = "LK", Name = "Lakers"};
nbaTeams[1] = new Team() {Id = 1, Initials = "OKC", Name = "Thunders"};
nbaTeams[2] = new Team() {Id = 1, Initials = "BOS", Name = "Boston"};
Enter fullscreen mode Exit fullscreen mode

The collection initializer allows add elements into the array and his size is the number of the items defined in the initializer.

Team[] nbaTeams = {
    new Team() {Id = 1, Initials = "LK", Name = "Lakers"},
    new Team() {Id = 2, Initials = "OKC", Name = "Thunders"},
    new Team() {Id = 3, Initials = "BOS", Name = "Boston"}
};
Enter fullscreen mode Exit fullscreen mode

Using the array name and [] with the index number we can access or modify an item in the array and using the .length property of return the total of items on it.

var okcTeam = nbaTeams[1];
Console.WriteLine(okcTeam.Name);

var cleveland = new Team() { Id = 1, Inials = "CLV", Name = "Cleveland"}
nbaTeams[0] = cleveland
Enter fullscreen mode Exit fullscreen mode

Use for or foreach statement to iterate over every element on the array.

foreach (var team in nbaTeams)
{
    Console.WriteLine($"{team.Name}");
}
Enter fullscreen mode Exit fullscreen mode

The Array helps to store data with order and fixed size but has a limitation because we can't change the size after the instantiation or add new elements before the initialization, for theses case the List come to help us.

The List

The list is very similar to the array, the initialization does not require the size, allow resize and provide methods like Add, Insert, Remove, RemoveAt, FindIndex and more, these methods help a lot when works with the elements in the List.

var nbaTeams = new List<Team> {
    new Team() {Id = 1, Initials = "LK", Name = "Lakers"},
    new Team() {Id = 2, Initials = "OKC", Name = "Thunders"},
    new Team() {Id = 3, Initials = "BOS", Name = "Boston"}
};
Enter fullscreen mode Exit fullscreen mode

The Add method allows appending an element into the end of the List and instead .length in the array, the list provides the Count property for return the number of elements, similar to the array.length.

nbaTeams.Add(new Team() {Id = 4, Initials = "CLP", Name = "Clippers"});
//or
var clippers = new Team() {Id = 4, Initials = "CLP", Name = "Clippers"};
nbaTeams.Add(clippers);
Enter fullscreen mode Exit fullscreen mode

To append an element into the middle or in the first position, use the method Insert and the index position to add an object into the list and with the FindIndex method you can look up the position using a lambda expression for setting the criteria of the search.

var sixers = new Team() {Id = 1, Initials = "SIX", Name = "Sixers"};

var indexTop = nbaTeams.FindIndex(t => t.Name == "Lakers");

nbaTeams.Insert(indexTop,sixers);
Enter fullscreen mode Exit fullscreen mode

The same when deleting an element, the Remove method needs the object to be removed or RemoveAt and need the index in terms of performance the RemoveAt is faster than Remove because it goes to the position instead iterate over the full list.

var clippers = new Team() {Id = 4, Initials = "CLP", Name = "Clippers"};

nbaTeams.Add(clippers);

var sixers = new Team() {Id = 1, Initials = "SIX", Name = "Sixers"};
var indexTop = nbaTeams.FindIndex(t => t.Name == "Lakers");

nbaTeams.Remove(clippers);

nbaTeams.RemoveAt(indexTop);
Enter fullscreen mode Exit fullscreen mode

The list is very similar to the Array and you can access the elements using for or foreach statement.

foreach (var team in nbaTeams)
{
    Console.WriteLine($"{team.Name}");
}
Enter fullscreen mode Exit fullscreen mode

The list is great when we don't know how many items will add to the collection and provide an easy method to work on that data but keep in mind the Insert and Delete methods need to move all elements to keep sync but it has a performance cost.

Dictionaries

The Dictionaries are great for unordered data and search by a key in short words the dictionaries are a box with items that can search using a key and similar to List it provides methods to able to Add, Remove, TryAdd, TryGetValue, Delete and properties like Count, Keys or Values.

The dictionary instantiating is a Dictionary that's mean a generic key and generic value, for example, the following code has a dictionary of string as key and Team object as value, the Add method uses the Initials as key and the same object lakers a Team object.

var teams = new Dictionary<string, Team>();
var lakers = new Team() {Id = 1, Initials = "LK", Name = "Lakers"};

teams.Add(lakers.Initials, lakers);
Enter fullscreen mode Exit fullscreen mode

For lookup data into the dictionary use the key or the TryGetValue method using an out parameter return true if you get the object or false.

var tempTeam = teams[LK];

Console.WriteLine(tempTeam.Name);

var containsKey = teams.TryGetValue("LK", out Team laks);

if (containsKey)
{
    Console.WriteLine(laks.Name);
}
Enter fullscreen mode Exit fullscreen mode

The Delete method expects an item is similar to try to get value.

var deleted = teams.Remove("LK", out Team d);

if (deleted) { 
   Console.WriteLine(d.Initials);
}
Enter fullscreen mode Exit fullscreen mode

To enumerate the elements into the Dictionary is not equals to Array or List, because it has 2 important points when iterating a dictionary, the element created in the foreach is a key value's type but it allows iterate over key values, keys or values.

foreach (var team in teams)
{
    Console.WriteLine($"{team.Key} {team.Value.Name}");
}

foreach (var team in teams.Values)
{
    Console.WriteLine($"{team.Name}");
}

foreach (var key in teams.Keys)
{
    Console.WriteLine($"{key}");
}
Enter fullscreen mode Exit fullscreen mode

Hopefully, that will give you a bit of a head-start on Collections in .NET.

Photo by Romain Vignes on Unsplash

Top comments (0)