c#取出两个liststudent里面Name不同的元素
你可以使用LINQ的Except方法来找出两个List
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
原文地址: https://www.cveoy.top/t/topic/iH8P 著作权归作者所有。请勿转载和采集!