【C# groupby的组合用法】

C# groupby + todictionary

C#数组同时使用groupby和todictionary方法,直接完成对象声明和分组

Dictionary<string,List<Student>> map = 
stus.GroupBy(stu => stu.ClassName)
.ToDictionary(s => s.Key,s => s.ToList());
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中,GroupBy 是一个 Linq 扩展方法,用于将一个集合按照指定的键进行分组。其基本用法如下: ```csharp IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector ) ``` 其中,source 表示要进行分组的集合,keySelector 表示用于提取分组键的函数。函数返回的结果相同的元素将被分到同一组中,最终返回一个实现了 IEnumerable<IGrouping<TKey, TSource>> 接口的集合,其中 IGrouping<TKey, TSource> 表示一个键与其对应的元素集合。 示例代码如下: ```csharp class Program { static void Main(string[] args) { var students = new List<Student>() { new Student() {Name = "Tom", Gender = Gender.Male, Age = 18}, new Student() {Name = "Jerry", Gender = Gender.Male, Age = 20}, new Student() {Name = "Lucy", Gender = Gender.Female, Age = 19}, new Student() {Name = "Lily", Gender = Gender.Female, Age = 21}, new Student() {Name = "Bob", Gender = Gender.Male, Age = 19}, new Student() {Name = "Alice", Gender = Gender.Female, Age = 18}, }; // 按照性别分组 var groups = students.GroupBy(s => s.Gender); foreach (var group in groups) { Console.WriteLine($"Gender: {group.Key}"); foreach (var student in group) { Console.WriteLine($" {student.Name}, {student.Age} years old."); } } // 按照年龄分组 groups = students.GroupBy(s => s.Age); foreach (var group in groups) { Console.WriteLine($"Age: {group.Key}"); foreach (var student in group) { Console.WriteLine($" {student.Name}, {student.Gender}."); } } Console.ReadLine(); } } enum Gender { Male, Female } class Student { public string Name { get; set; } public Gender Gender { get; set; } public int Age { get; set; } } ``` 输出结果如下: ``` Gender: Male Tom, 18 years old. Jerry, 20 years old. Bob, 19 years old. Gender: Female Lucy, 19 years old. Lily, 21 years old. Alice, 18 years old. Age: 18 Tom, Male. Alice, Female. Age: 20 Jerry, Male. Age: 19 Lucy, Female. Bob, Male. Age: 21 Lily, Female. ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值