當前位置: 妍妍網 > 碼農

.NET 9 Preview 1 中 Linq 更新

2024-02-26碼農

.NET 9 Preview 1 中 Linq 更新

Intro

.NET 9 Preview 1 中在之前的 .NET 版本的基礎上又新增了一些 Linq 方法的支持

Index

.NET 9 裏引入了一個 Index 的 Linq 方法,我們可以在 foreach 的時候獲取到對應的 Index

類似於使用 Select((index, item) => ) ,更簡單一些,範例如下:

var employees = Enumerable.Range(110)
.Select(x => new
{
Id = x, 
Level = x % 4
Name = $"xxx {x}"
Score = x * 10
})
.ToArray();
// Index
Console.WriteLine("Index sample:");
foreach (var (index, item) in employees.Index())
{
Console.WriteLine($"Index: {index}, Id: {item.Id}{JsonSerializer.Serialize(item)}");
}

輸出結果如下:

IndexSample output

CountBy

在 .NET 6 中引入了一系列的 XxxBy 系列的 Linq 方法如: MaxBy / MinBy / DistinctBy ...

在 .NET 9 裏也引入了 CountBy AggregateBy 的擴充套件

先來看下 CountBy 的範例,還是使用之前的數據:

Console.WriteLine("CountBy sample:");
foreach (var (key, count) in employees.CountBy(x => x.Level))
{
Console.WriteLine($"Level {key}, Count: {count}");
}

這裏我們按照 Level 做一個 Count,相當於按 Level 做一個 GroupBy,輸出結果如下:

CountBy sample

AggregateBy

AggregateBy 使用範例如下:

Console.WriteLine("AggregateBy sample:");
foreach (var (key, total) in employees.AggregateBy(s => s.Level, 0, (a, x) => a + x.Score))
{
Console.WriteLine($"Level {key}: Total: {total}");
}
Console.WriteLine();
foreach (var (key, total) in employees.AggregateBy(s => s.Level, x => x * 10, (a, x) => a + x.Score))
{
Console.WriteLine($"Level {key}: Total: {total}");
}

Aggregate 可以按照有一個 seed,第一個範例中 seed 是 0,第二個範例根據 aggregate 的欄位來設定,輸出結果如下:

第一個例子相當於按 level 做了一個 groupBy 之後,group 裏按 score 取了一個 Sum

第二個例子在第一個例子的基礎之上,修改了 seed,相當於在 Sum 的基礎上又加上了 level * 10

References

  • https://github.com/dotnet/runtime/issues/95563

  • https://github.com/dotnet/runtime/pull/95947

  • https://github.com/dotnet/runtime/issues/77716

  • https://github.com/dotnet/runtime/pull/91507

  • https://github.com/dotnet/runtime/issues/91533

  • https://github.com/dotnet/runtime/pull/92089

  • https://github.com/WeihanLi/SamplesInPractice/blob/main/net9sample/Net9Samples/LinqSample.cs