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:
csharpList<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.
C# offers several ways to initialize the collection concisely.
In c#, an array can be initialized directly in the following syntax.
csharpint[] numbers = { 1, 2, 3, 4, 5 };
In c#, Lists and other collections can be initialized similarly using collection initializers:
csharpList<string> names = new List<string> { "Alice", "Bob", "Charlie" };
In c#, the Dictionary can be initialized directly, using the key-value pairs:
csharpDictionary<int, string> employees = new Dictionary<int, string> { { 1, "John" }, { 2, "Jane" }, { 3, "Doe" } };
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#:
You can convert a List<T> to an array using the ToArray() method:
csharpList<int> numbersList = new List<int> { 1, 2, 3, 4, 5 }; int[] numbersArray = numbersList.ToArray();
Similarly, converting an array to a list can be done with the ToList() method:
csharpint[] numbersArray = { 1, 2, 3, 4, 5 }; List<int> numbersList = numbersArray.ToList();
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.
csharpList<int> numbersList = new List<int> { 1, 2, 3, 3, 4 }; // Removes duplicates HashSet<int> numbersSet = numbersList.ToHashSet();
csharpList<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.
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();
In the following example, we perform a collection expression for dictionary initialization:
csharpusing 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
In this example, we initialization an array with Collection Expression:
csharpusing 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
In this example, create and manipulate the collection with LINQ:
csharpusing 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
Copyrights © 2024 letsupdateskills All rights reserved