.NET 9中 LINQ的增强功能

作者:微信公众号:【架构师老卢】
7-4 14:3
135

在最新的 .NET 9 预览版中,引入了两种令人兴奋的 LINQ 方法:

CountBy()

  • 根据特定键对元素进行计数。
  • 通过对元素进行分组和提供计数来简化计数任务。

优点:.CountBy

  1. 简单易读性:
  • 该方法简化了按键对元素进行分组和计算出现次数的过程。.CountBy
  • 它直接返回一个集合,其中键表示组,值是该组中的元素计数。KeyValuePair<TKey, int>
  • 这样可以生成更清晰、更直观的代码。

2**. 降低复杂性:**

  • 在引入之前,开发人员必须依赖于 and(或)方法的组合。.CountBy.GroupBy.Select.Count
  • 前一种方法涉及更多代码,不太简单。

上一种方法(.NET 9 之前):

 public class User
 {
     public string? Name { get; set; }
     public string? Role { get; set; }
 }
 internal class Program
 {
     static void Main(string[] args)
     {
        // Define a list of users
         var users = new List<User>
     {
         new User { Name = "Alice", Role = "Admin" },
         new User { Name = "Bob", Role = "Member" },
         new User { Name = "Jay", Role = "Member" },
         new User { Name = "Krishna", Role = "Admin" },
         new User { Name = "An", Role = "Member" },
         new User { Name = "Ka", Role = "Guest" },
         
     };

         // CountBy Role using GroupBy and Select
         var roleCounts = users
             .GroupBy(user => user.Role) // Group users by their roles
             .Select(group => new { Role = group.Key, Count = group.Count() }); // Select the role and count for each group
          
      // Print the results
         foreach (var roleCount in roleCounts)
         {
             Console.WriteLine($"Role: {roleCount.Role}, Count: {roleCount.Count}");
         }
     }
 }

在 .NET 9 中使用:.CountBy

// With .NET 9, the same operation can be achieved with cleaner code  
foreach (var roleCount in users.CountBy(user => user.Role))  
{  
    Console.WriteLine($"There are {roleCount.Value} users with the role {roleCount.Key}");  
}

输出将是:

There are 3 users with the role Member  
There are 2 users with the role Admin  
There is 1 user with the role Guest

聚合作者

好处

  • 该方法简化了按键对元素进行分组并基于该键聚合值的过程。.AggregateBy
  • 它直接返回一个集合,其中键表示组,值是聚合操作的结果。KeyValuePair<TKey, TValue>

降低复杂性:

在引入之前,开发人员必须使用循环或多个 LINQ 方法手动实现自定义聚合逻辑。.AggregateBy

上一种方法(.NET 9 之前):

// Example: Summing numbers using a loop
var numbers = new List<int> { 1, 2, 3, 4 };
var sum = 0;
foreach (var number in numbers)
{
    sum += number;
}
Console.WriteLine($"Sum: {sum}");

在 .NET 9 中使用:.AggregateBy

// Example: Summing numbers using .AggregateBy
var numbers = new List<int> { 1, 2, 3, 4 };
var totalSum = numbers.AggregateBy(n => "Total", (acc, number) => acc + number);
Console.WriteLine($"Total Sum: {totalSum.Value}");

输出将是:

Total Sum: 10

总而言之,使用并使您的代码更加简洁和富有表现力。它是 .NET 9 中 LINQ 的宝贵补充!

相关留言评论
昵称:
邮箱:
阅读排行