C# 中List分组、排序、动态分组
定义实体类
language
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Grade { get; set; }
}
按单个属性分组
language
class Program
{
static void Main()
{
List<Student> students = new List<Student>
{
new Student { Name = "Alice", Age = 25, Grade = "A" },
new Student { Name = "Bob", Age = 22, Grade = "B" },
new Student { Name = "Charlie", Age = 24, Grade = "A" },
new Student { Name = "David", Age = 23, Grade = "B" }
};
//1、语言集成查询 (LINQ) group 分组
var groupedByGrade =
from student in students
group student by student.Grade into newGroup
//orderby newGroup.Key
select newGroup;
foreach (var group in groupedByGrade)
{
Console.WriteLine($"Grade: {group.Key}");
foreach (var student in group)
{
Console.WriteLine($"Name: {student.Name}, Age: {student.Age}");
}
}
}
}
使用方法语法的等效代码分组
language
v ar groupByYearQuery = students
.GroupBy(student => student.Grade)
//.OrderBy(newGroup => newGroup.Key);
foreach (var yearGroup in groupByYearQuery)
{
Console.WriteLine($"Key: {yearGroup.Key}");
foreach (var student in yearGroup)
{
Console.WriteLine($"\t{student.LastName}, {student.FirstName}");
}
}
排序
记住这么用就对了
OrderBy:students.OrderBy(s => s.Age).ToList(); // 升序
OrderByDescending: students.OrderByDescending(s => s.Age).ToList();//倒序
分组
这是个扩展方法,因为使用this。keySelector 就是个函数 ,表示用哪个键分组、并返回一个TKey类型的结果。 GroupedEnumerable 类来进行实际的分组操作返回一个实现了 IEnumerable<IGrouping<TKey, TSource>> 接口的结果集合。
language
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
return new GroupedEnumerable<TSource, TKey, TSource>(source, keySelector, IdentityFunction<TSource>.Instance, null);
}
官网链接
其中也有要多个属性分组的示例,也就是嵌套分组吧
对数据分组 (C#)
JAVA 中的List分组、排序及动态分组排序
分组
language
class Main {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", 25, "A"),
new Student("Bob", 22, "B"),
new Student("Charlie", 24, "A"),
new Student("David", 23, "B")
);
Map<String, List<Student>> groupedByGrade = students.stream()
.collect(Collectors.groupingBy(Student::getGrade));
groupedByGrade.forEach((grade, list) -> {
System.out.println("Grade: " + grade);
list.forEach(s -> System.out.println("Name: " + s.getName() + ", Age: " + s.getAge()));
});
}
}
升序和倒序
原理就慢慢再懂吧。记住用就行
language
List<Student> sortedStudent = students.stream()
.sorted(Comparator.comparing(Student::getAge))
.collect(Collectors.toList()); //升序
List<Student> sortedStudent = students.stream()
.sorted(Comparator.comparing(Student::getAge).reversed())
.collect(Collectors.toList()); //倒序
简简单单的记录一下自己在.net转java过程中遇到的一些知识点,不是很深
写的有不对或者理解不深刻的地方,请各位老师多多的提,非常感谢!
老师们,同伟太想进步了!!!