.NET 6 中 LINQ 的改進

.NET 6 中 LINQ 的改進

如題

最後更新 2022/4/23 下午2:29
一个小伙子
預計閱讀 3 分鐘
分類
.NET
標籤
.NET C# LINQ

1. OrDefault 方法的預設值

Enumerable.FirstOrDefault 方法會傳回序列的第一個元素,如果找不到,則傳回預設值。在 .NET 6 中,你可以覆寫該方法的預設值。同樣地,你也可以覆寫 SingleOrDefaultLastOrDefault 方法的預設值。

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);
// 輸出:Product { Name = Product2, Price = 5 }
Console.WriteLine(theMostExpensiveProduct);
// 輸出:Product { Name = Product1, Price = 100 }

record Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

3. 三向 Zip 方法

Enumerable.Zip 擴充方法可以將兩個序列進行結合,產生一個二元組序列。在 .NET 6 中,它可以結合三個序列,產生一個三元組序列。

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}");
}
// 輸出:
// 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);
// 輸出:
// 3
// 4

IEnumerable<int> taken2 = numbers.Take(..3);
foreach (int i in taken2)
    Console.WriteLine(i);
// 輸出:
// 1
// 2
// 3

IEnumerable<int> taken3 = numbers.Take(3..);
foreach (int i in taken3)
    Console.WriteLine(i);
// 輸出:
// 4
// 5
繼續探索

延伸閱讀

更多文章
同分類 / 同標籤 2026/2/7

AOT使用經驗總結

從專案建立伊始,就應養成良好的習慣,即只要添加了新功能或使用了較新的語法,就及時進行 AOT 發布測試。

繼續閱讀