可以使用LINQ来实现这个功能。首先,我们可以使用GroupBy方法将List<Student>按照名称进行分组。然后,对于每个分组,我们可以使用OrderBy方法将日期按照降序排列,并使用Skip方法跳过第一个元素(即日期比较新的那个)。最后,我们可以使用SelectMany方法将所有分组的元素合并为一个新的List<Student>

以下是一个示例代码:

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类,其中包含NameDateOfBirth属性。然后,我们创建了一个包含多个学生的List<Student>。通过使用LINQ的GroupBy方法,我们将学生按照名称进行分组。然后,对于每个分组,我们使用OrderByDescending方法将学生按照日期进行降序排列,然后使用Skip方法跳过第一个元素。最后,我们使用SelectMany方法将所有分组的学生合并为一个新的List<Student>。最后,我们遍历新的列表并打印每个学生的名称和出生日期

c#查找LISTstudent里面重复名称的项将日期比较旧的那项删除

原文地址: https://www.cveoy.top/t/topic/ixzm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录