c# 将LISTSTUDENT里面名称重复的元素找出保留日期最新的删掉多余重复名称的
您可以使用LINQ查询来实现这个功能。首先,您需要按名称进行分组,然后在每个组中选择日期最新的元素。最后,您可以使用RemoveAll方法删除多余的元素。
下面是一个示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
public class Student
{
public string Name { get; set; }
public DateTime Date { get; set; }
}
public class Program
{
public static void Main()
{
List<Student> students = new List<Student>
{
new Student { Name = "Alice", Date = new DateTime(2022, 1, 1) },
new Student { Name = "Bob", Date = new DateTime(2022, 2, 1) },
new Student { Name = "Alice", Date = new DateTime(2022, 3, 1) },
new Student { Name = "Charlie", Date = new DateTime(2022, 4, 1) },
new Student { Name = "Bob", Date = new DateTime(2022, 5, 1) },
new Student { Name = "Alice", Date = new DateTime(2022, 6, 1) }
};
var result = students
.GroupBy(s => s.Name)
.Select(g => g.OrderByDescending(s => s.Date).First())
.ToList();
students.RemoveAll(s => !result.Contains(s));
foreach (var student in students)
{
Console.WriteLine($"Name: {student.Name}, Date: {student.Date}");
}
}
}
在上面的示例中,我们首先创建了一个包含学生信息的列表。然后,我们使用LINQ的GroupBy方法按名称进行分组,然后使用Select方法选择每个组中日期最新的元素。最后,我们使用RemoveAll方法删除多余的元素。
输出结果为:
Name: Bob, Date: 2022/05/01
Name: Alice, Date: 2022/06/01
Name: Charlie, Date: 2022/04/01
在这个例子中,Bob和Alice的重复名称已被删除,并且只保留了日期最新的元素
原文地址: http://www.cveoy.top/t/topic/ixFX 著作权归作者所有。请勿转载和采集!