.NET 9中 LINQ的增强功能

6b912d116062ed3afea987e257e3068b.png

在最新的 .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 的宝贵补充!

如果你喜欢我的文章,请给我一个赞!谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值