你可以使用LINQ的Except方法来找出两个List中Name不同的元素。以下是一个示例代码:

using System;
using System.Collections.Generic;
using System.Linq;

public class Student
{
    public string Name { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        List<Student> list1 = new List<Student>()
        {
            new Student() { Name = "John" },
            new Student() { Name = "Alice" },
            new Student() { Name = "Bob" }
        };

        List<Student> list2 = new List<Student>()
        {
            new Student() { Name = "John" },
            new Student() { Name = "Alice" },
            new Student() { Name = "Charlie" }
        };

        var differentStudents = list1.Except(list2, new StudentNameComparer());

        foreach (var student in differentStudents)
        {
            Console.WriteLine(student.Name);
        }
    }
}

public class StudentNameComparer : IEqualityComparer<Student>
{
    public bool Equals(Student x, Student y)
    {
        return x.Name == y.Name;
    }

    public int GetHashCode(Student obj)
    {
        return obj.Name.GetHashCode();
    }
}

在上面的示例中,我们创建了两个List对象(list1和list2),并使用Except方法找出list1中Name不同于list2的元素。为了比较Student对象的Name属性,我们实现了一个自定义的StudentNameComparer类,该类实现了IEqualityComparer接口。在Main方法中,我们使用differentStudents变量来保存不同的学生对象,并通过循环遍历打印出这些学生的姓名

c#取出两个liststudent里面Name不同的元素

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

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