Collection expressions in CSharp

Collection expressions in C# are a relatively new feature that simplifies the initialization of collections like lists, arrays, and dictionaries. These expressions provide a more concise and readable way to work with collections. They help in initializing collections more compactly by using bracket syntax [] rather than traditional approaches.

A collection expression contains a sequence of elements enclosed within brackets []. Here's a simple code:

csharp
List<int> evenNumbers = [2, 4, 6, 8, 10];

The above syntax demonstrates the initialization of list<int> using collection expression, which makes the code more concise compared to traditional list declaration.

You can use a collection expression to create generic collection values. Collections are reduced syntax that can be tested and assigned to a wide variety of collections.

Collection Initialization

C# offers several ways to initialize the collection concisely.

Array Initializer

In c#, an array can be initialized directly in the following syntax.

csharp
int[] numbers = { 1, 2, 3, 4, 5 };

List Initializer

In c#, Lists and other collections can be initialized similarly using collection initializers:

csharp
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

Dictionary Initializer

In c#, the Dictionary can be initialized directly, using the key-value pairs:

csharp
Dictionary<int, string> employees = new Dictionary<int, string> { { 1, "John" }, { 2, "Jane" }, { 3, "Doe" } };

Conversion

A collection conversion refers to the conversion of one type of collection to another or the conversion of items in a collection. In C#, this can be done in a variety of ways, using LINQ or specific conversion methods provided by the .NET framework. Here's how you can handle collection changes in C#:

Convert List<T> to Array

You can convert a List<T> to an array using the ToArray() method:

csharp
List<int> numbersList = new List<int> { 1, 2, 3, 4, 5 }; int[] numbersArray = numbersList.ToArray();

Convert Array to List<T>

Similarly, converting an array to a list can be done with the ToList() method:

csharp
int[] numbersArray = { 1, 2, 3, 4, 5 }; List<int> numbersList = numbersArray.ToList();

LINQ-based Conversions

LINQ (Language-Integrated Query) provides numerous methods to convert collections, manipulate their elements, and project the data into new forms.

You can convert a collection into other collection types like HashSet, Dictionary, etc., using the ToHashSet(), ToDictionary(), and ToList() methods.

Convert List to HashSet:

csharp
List<int> numbersList = new List<int> { 1, 2, 3, 3, 4 }; // Removes duplicates HashSet<int> numbersSet = numbersList.ToHashSet();

Convert List to Dictionary (using key-value pairs):

csharp
List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; Dictionary<int, string> namesDict = names.ToDictionary(name => name.Length, name => name);

Here, the key is the length of the name; the value is the name itself.

Select Transformation

LINQ’s Select() allows objects in a collection to be changed to another form:

csharp
// Transform each element var squares = numbersList.Select(x => x * x).ToList();

Example

In the following example, we perform a collection expression for dictionary initialization:

csharp
using System; using System.Collections.Generic; public class Example { public static void Main(string[] args) { var employees = new Dictionary<int, string>{ [101] = "Alice", [102] = "Bob", [103] = "Charlie" }; foreach (var kvp in employees) { Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}"); } } }.

Output

ID: 101, Name: Alice
ID: 102, Name: Bob
ID: 103, Name: Charlie

Example

In this example, we initialization an array with Collection Expression:

csharp
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main(string[] args) { int[] numbers = { 1, 2, 3, 4, 5 }; // Transform the array by multiplying each number by 10 int[] multipliedNumbers = numbers.Select(n => n * 10).ToArray(); foreach (var number in multipliedNumbers) { Console.Write(number+" "); // Prints: 10, 20, 30, 40, 50 } } }

Output

10, 20, 30, 40, 50

Example

In this example, create and manipulate the collection with LINQ:

csharp
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main(string[] args) { List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // using LINQ: filter even numbers and square them var evenSquares = numbers // Filter even numbers .Where(n => n % 2 == 0) // Square the numbers .Select(n => n * n) // Convert the result back to a List .ToList(); // Output the result foreach (var square in evenSquares) { Console.Write(square + " "); } } }

Output

4 16 36 64 100

line

Copyrights © 2024 letsupdateskills All rights reserved