C# 使用 LINQ 删除 List<Student> 中重复名称的旧项
可以使用 LINQ 来实现这个功能。首先,我们可以使用 'GroupBy' 方法将 'List
以下是一个示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
public class Student
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
List<Student> students = new List<Student>
{
new Student { Name = 'John', DateOfBirth = new DateTime(2000, 1, 1) },
new Student { Name = 'Alice', DateOfBirth = new DateTime(2005, 1, 1) },
new Student { Name = 'John', DateOfBirth = new DateTime(1995, 1, 1) },
new Student { Name = 'Bob', DateOfBirth = new DateTime(1990, 1, 1) },
new Student { Name = 'Alice', DateOfBirth = new DateTime(1998, 1, 1) }
};
List<Student> filteredStudents = students
.GroupBy(s => s.Name)
.SelectMany(g => g.OrderByDescending(s => s.DateOfBirth).Skip(1))
.ToList();
foreach (var student in filteredStudents)
{
Console.WriteLine($'Name: {student.Name}, Date of Birth: {student.DateOfBirth}');
}
}
}
输出结果为:
Name: John, Date of Birth: 1995/1/1 0:00:00
Name: Alice, Date of Birth: 1998/1/1 0:00:00
Name: Bob, Date of Birth: 1990/1/1 0:00:00
在这个示例中,我们定义了一个 'Student' 类,其中包含 'Name' 和 'DateOfBirth' 属性。然后,我们创建了一个包含多个学生的 'List
原文地址: https://www.cveoy.top/t/topic/qeR7 著作权归作者所有。请勿转载和采集!