1. OrDefault メソッドの既定値
Enumerable.FirstOrDefault メソッドは、シーケンスの最初の要素を返します。要素が見つからない場合は、既定値を返します。.NET 6 では、このメソッドの既定値をオーバーライドできます。同様に、SingleOrDefault および LastOrDefault メソッドの既定値もオーバーライドできます。
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. 新しい By メソッド
- 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. 3方向の Zip メソッド
Enumerable.Zip 拡張メソッドは、2つのシーケンスを結合してタプルのシーケンスを生成します。.NET 6 では、3つのシーケンスを結合して3要素タプルのシーケンスを生成できます。
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 メソッドが Range をサポート
.NET Core 3.0 では Range 構造体が導入され、C# コンパイラは範囲演算子 .. をサポートするためにこれを使用します。.NET 6 では、Enumerable.Take メソッドも 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