• LINQ中CountBy方法和AggregateBy方法的使用方式
  • 发布于 2个月前
  • 70 热度
    0 评论
LINQ 介绍
语言集成查询 (LINQ) 是一系列直接将查询功能集成到 C# 语言的技术统称。 数据查询历来都表示为简单的字符串,没有编译时类型检查或 IntelliSense 支持。 此外,需要针对每种类型的数据源了解不同的查询语言:SQL 数据库、XML 文档、各种 Web 服务等。 借助 LINQ,查询成为了最高级的语言构造,就像类、方法和事件一样。

.NET 9 环境准备
需要体验 .NET 9 中 LINQ 的新增功能前提是需要安装 .NET 9 环境,安装 .NET 9 SDK 并且Visual Studio 2022需要更新至17.12版本。
下载.NET 9.0:https://dotnet.microsoft.com/zh-cn/download/dotnet/9.0

CountBy方法
CountBy这个方法允许开发者按键来聚合集合中的元素,并计算每个键的出现次数。这使得计算某个数据集中特定元素的频率变得非常简单。
        public static void CountByExample()
        {
            var sourceText = "This is a test text. This is only a test. This is the best. This,This,This";
            // 堆代码 duidaima.com
            // 统计每个单词出现的次数
            KeyValuePair<string, int> mostFrequentWord = sourceText
            .Split([' ', '.', ','], StringSplitOptions.RemoveEmptyEntries)
            .Select(word => word.ToLowerInvariant())
            .CountBy(word => word)
            .MaxBy(pair => pair.Value);

            Console.WriteLine($"最常见的词是:'{mostFrequentWord.Key}' 出现次数: {mostFrequentWord.Value}");
        }
输出结果:

AggregateBy方法
AggregateBy这个方法提供了更强大的聚合功能,开发者可以定义一个聚合逻辑(如求和、平均值等),并按键进行聚合。该方法在需要基于键对集合中的元素进行复杂计算时非常有用。
        public static void AggregateByExample()
        {
            (string id, int score)[] data =
                [
                ("0", 88),
                ("1", 5),
                ("2", 4),
                ("1", 10),
                ("6", 5),
                ("4", 10),
                ("6", 25)];

            // aggregatedData 是一个序列,包含按姓名分组并计算总分的元素
            var aggregatedData =
                data.AggregateBy(
                    keySelector: entry => entry.id,
                    seed: 0,
                    (totalScore, curr) => totalScore + curr.score
                    );

            foreach (var item in aggregatedData)
            {
                Console.WriteLine(item);
            }
        }
输出结果:

Index<TSource>(IEnumerable<TSource>) 方法
借助 Index<TSource>(IEnumerable<TSource>),可以快速提取可枚举项的隐式索引。 现在,可以编写代码(如以下代码片段)来自动为集合中的项编制索引。
        public static void IndexExample()
        {
            var lines = new List<string> { "First line", "Second line", "Third line" };
            foreach (var (index, line) in lines.Index())
            {
                Console.WriteLine($"Line {index + 1}: {line}");
            }
        }
输出结果:

参考文章
https://learn.microsoft.com/zh-cn/dotnet/core/whats-new/dotnet-9/overview#linq
用户评论