DEV Community

Nitish Prajapati
Nitish Prajapati

Posted on

C# Collection Framework

For many applications, we want to create and manage groups of related objects.
There are two ways to group objects:-

Image description

Arrays are most useful for creating and working with a fixed number of strongly typed objects.

Collections provide a more flexible way to work with groups of objects. Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change. For some collections, you can assign a key to any object that you put into the collection so that you can quickly retrieve the object by using the key.

A collection is a class, so you must declare an instance of the class before you can add elements to that collection.

Generally there are 3 types of Collections:-

  1. System.Collections.Generic Classes
  2. System.Collections.Concurrent Classes
  3. System.Collections.Classes

Let's start with using a Simple Collection:-
We will be Implementing the generic List class , which enables you to work with a strongly types list of objects.

//Creating a list of strings
var salmons = new List<string>();
salmons.Add("chinook");
salmons.Add("coho");
salmons.Add("pink");
salmons.Add("sockeye");

// Iterate through the list.
foreach(var salmon in salmons)
{
    Console.Write(salmon + " ");
}
//Result: chinook coho pink sockeye
Enter fullscreen mode Exit fullscreen mode

If the contents of a collection are known in advance, you can use a collection initializer to initialize the collection.

// Create a list of strings by using a
// collection initializer.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };

// Iterate through the list.
foreach (var salmon in salmons)
{
    Console.Write(salmon + " ");
}
// Output: chinook coho pink sockeye

Enter fullscreen mode Exit fullscreen mode

You can use a for statement instead of a foreach statement to iterate through a collection. You accomplish this by accessing the collection elements by the index position. The index of the elements starts at 0 and ends at the element count minus 1.

The following example iterates through the elements of a collection by using for instead of foreach.

// Create a list of strings by using a
// collection initializer.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };

for (var index = 0; index < salmons.Count; index++)
{
    Console.Write(salmons[index] + " ");
}
// Output: chinook coho pink sockeye

Enter fullscreen mode Exit fullscreen mode

The following example removes an element from the collection by specifying the object to remove.

// Create a list of strings by using a
// collection initializer.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };

// Remove an element from the list by specifying
// the object.
salmons.Remove("coho");

// Iterate through the list.
foreach (var salmon in salmons)
{
    Console.Write(salmon + " ");
}
// Output: chinook pink sockeye

Enter fullscreen mode Exit fullscreen mode

The following example removes elements from a generic list. Instead of a foreach statement, a for statement that iterates in descending order is used. This is because the RemoveAt method causes elements after a removed element to have a lower index value.

var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Remove odd numbers.
for (var index = numbers.Count - 1; index >= 0; index--)
{
    if (numbers[index] % 2 == 1)
    {
        // Remove the element by specifying
        // the zero-based index in the list.
        numbers.RemoveAt(index);
    }
}

// Iterate through the list.
// A lambda expression is placed in the ForEach method
// of the List(T) object.
numbers.ForEach(
    number => Console.Write(number + " "));
// Output: 0 2 4 6 8

Enter fullscreen mode Exit fullscreen mode

For the type of elements in the List, you can also define your own class. In the following example, the Galaxy class that is used by the List is defined in the code.

private static void IterateThroughList()
{
    var theGalaxies = new List<Galaxy>
        {
            new Galaxy() { Name="Tadpole", MegaLightYears=400},
            new Galaxy() { Name="Pinwheel", MegaLightYears=25},
            new Galaxy() { Name="Milky Way", MegaLightYears=0},
            new Galaxy() { Name="Andromeda", MegaLightYears=3}
        };

    foreach (Galaxy theGalaxy in theGalaxies)
    {
        Console.WriteLine(theGalaxy.Name + "  " + theGalaxy.MegaLightYears);
    }

    // Output:
    //  Tadpole  400
    //  Pinwheel  25
    //  Milky Way  0
    //  Andromeda  3
}

public class Galaxy
{
    public string Name { get; set; }
    public int MegaLightYears { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Further we will discuss more about the different classes in Collection framework.

Top comments (0)