.Net

Arrays and collections – Part 2

Overview of collections

In the preceding section, we delved into C# arrays. As a quick recap, arrays are excellent for scenarios where you have a predetermined set of elements, all of the same type, and know precisely how many you require. However, the real world often necessitates a more dynamic and adaptable approach to data management. This is where collections step in, offering increased flexibility compared to arrays. Unlike arrays, collections can accommodate a variety of elements and adjust in size dynamically. To ensure order and type consistency within this dynamic environment, we’ll explore the concept of “Generic.” Now, let’s transition our focus to collections.

Type of collections in C#

In C#, we encounter two main categories of collections: generic and non-generic collections. In this comparison table, I have consolidated the major differences between the two families.

AspectGeneric CollectionsNon-Generic Collections
NamespaceSystem.Collections.GenericsSystem.Collections
TypeStrongly typedNot strongly typed
Storing ElementsInternally uses arrays of actual typesInternally uses object arrays
Type SafetyProvides type safety without derivationSpecialized classes for data storage
This table summarizes the key differences between generic and non-generic collections in terms of namespace, type, storing elements, and type safety.
Non-Generic CollectionsGeneric Collections
ArrayListList<T>
HashTableDictionary<TKey, TValue>
StoredListSortedList<TKey, TValue>
StackStack<T>
QueueQueue<T>

A Guide to Generic Collections in C#

Both types of collections, generic and non-generic, implement the following common functionality. So, the functionalities that we will explore in this chapter, available for non-generic collections, include:

  • Adding and inserting items into collection
  • Replacing and removing items from collection.
  • Sorting and searching for items
  • Coping and cloning collections and items
  • Using the capacity of Count properties to determinate the collection’s capacity and the number of items it contains.
Building generic collection using C#

Building a new generic list of type string using various collection types :

List : Dynamic arrays that can grow or shrink in size. They allow fast access to elements and are useful when the order of elements matters.

Dictionary : Dictionaries are key-value pairs that provide a way to associate unique keys with values. They are efficient for fast retrieval of values based on their corresponding keys.

SortedList : SortedLists are collections that maintain elements in sorted order based on their keys. They combine the features of a dictionary and a list, providing quick access and ordered storage.

Stack : Stacks follow the Last In, First Out (LIFO) principle, where the last element added is the first to be removed

Queue : Queues follow the First In, First Out (FIFO) principle, where the first element added is the first to be removed.

Data manipulation with generic collections

Let’s consider a simpler use case involving a generic list of integers to represent scores of participants in a competition. We’ll perform basic data manipulation tasks such as adding score, finding highest score, removing specific score, filtering participants based on their scores, sorting scores in ascending order and clearing all scores.

If you noticed the 'params' keyword in the AddScores method and you are not sure what it does, here is a simple explanation : The 'params' keyword lets you say that a method can take different numbers of things. In the AddScores method, 'params' is used so you can give the method any number of integer values. when you see 'params int[] newScores', it means that the method can take zero or more integers. these integers are then treated like an array named newScore ( in out case ).

What's your reaction?

Excited
0
Happy
0
In Love
0
Not Sure
0
Silly
0
MBensaid
Hello, I'm Mohammed, a passionate developer. I share my enthusiasm and knowledge on MBenSaid to inspire fellow enthusiasts. Together, let's build a bright digital future!

    Leave a reply

    Your email address will not be published. Required fields are marked *

    Next Article:

    0 %