1. Default Value for OrDefault Methods
The Enumerable.FirstOrDefault method returns the first element of a sequence, or a default value if none is found. In .NET 6, you can override the default value for this method. Similarly, you can override the default value for SingleOrDefault and LastOrDefault methods.
List<int> list1 = new() { 1, 2, 3 };
int item1 = list1.FirstOrDefault(i => i == 4, -1);
Console.WriteLine(item1); // -1
List<string> list2 = new() { "Item1" };
string item2 = list2.SingleOrDefault(i => i == "Item2", "Not found");
Console.WriteLine(item2); // Not found
2. New By Methods
- MinBy
- MaxBy
- DistinctBy
- ExceptBy
- IntersectBy
- UnionBy
List<Product> products = new()
{
new() { Name = "Product1", Price = 100 },
new() { Name = "Product2", Price = 5 },
new() { Name = "Product3", Price = 50 },
};
Product theCheapestProduct = products.MinBy(x => x.Price);
Product theMostExpensiveProduct = products.MaxBy(x => x.Price);
Console.WriteLine(theCheapestProduct);
// Output: Product { Name = Product2, Price = 5 }
Console.WriteLine(theMostExpensiveProduct);
// Output: Product { Name = Product1, Price = 100 }
record Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
3. Three-Way Zip Method
The Enumerable.Zip extension method combines two sequences to produce a sequence of tuples. In .NET 6, it can combine three sequences to produce a sequence of triplets.
int[] numbers = { 1, 2, 3, 4, };
string[] months = { "Jan", "Feb", "Mar" };
string[] seasons = { "Winter", "Winter", "Spring" };
var test = numbers.Zip(months).Zip(seasons);
foreach ((int, string, string) zipped in numbers.Zip(months, seasons))
{
Console.WriteLine($"{zipped.Item1} {zipped.Item2} {zipped.Item3}");
}
// Output:
// 1 Jan Winter
// 2 Feb Winter
// 3 Mar Spring
4. Take Method Supporting Range
The Range struct was also introduced in .NET Core 3.0 and is used by the C# compiler to support the range operator ... In .NET 6, the Enumerable.Take method also supports Range.
IEnumerable<int> numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> taken1 = numbers.Take(2..4);
foreach (int i in taken1)
Console.WriteLine(i);
// Output:
// 3
// 4
IEnumerable<int> taken2 = numbers.Take(..3);
foreach (int i in taken2)
Console.WriteLine(i);
// Output:
// 1
// 2
// 3
IEnumerable<int> taken3 = numbers.Take(3..);
foreach (int i in taken3)
Console.WriteLine(i);
// Output:
// 4
// 5