我正在尝试使用csharp和linq
比较2个列表我想拉的典型场景是
检查第二个列表中的值是否大于第一个列表中的值,即第一个列表=第二个列表,第二个列表的值是否超过第一个列表。
class Program
{
static void Main(string[] args)
{
List<Student> studentsSrcList = new List<Student>();
Student s1 = new Student();
s1.Name = "john1";
s1.Address = "milwaukee1";
s1.Phone = 1061;
studentsSrcList.Add(s1);
Student s2 = new Student();
s2.Name = "john2";
s2.Address = "milwaukee2";
s2.Phone = 1062;
studentsSrcList.Add(s2);
List<Student> studentDestinationList = new List<Student>();
Student s3 = new Student();
s3.Name = "john1";
s3.Address = "milwaukee1";
s3.Phone = 1061;
studentDestinationList.Add(s3);
Student s4 = new Student();
s4.Name = "john3";
s4.Address = "milwaukee2";
s4.Phone = 1064;
studentDestinationList.Add(s4);
Student s5 = new Student();
s5.Name = "john5";
s5.Address = "milwaukee5";
s5.Phone = 1065;
studentDestinationList.Add(s5);
var diff = studentDestinationList.Intersect(studentsSrcList);
}
}
class Student
{
public string Name { get; set; }
public string Address { get; set; }
public int Phone { get; set; }
}
我也试过var diff = studentsSrcList.SequenceEqual(studentsDestinationList);
答案 0 :(得分:1)
比较引用类型的实例时.Net默认比较引用,而不是内容。在您的示例中,s1和s3是不同的实例,因此它们不相等。
您可以在Student类中重写Equals方法,或者使其实现IEquatable接口,以便比较类中的值。
答案 1 :(得分:1)
您必须定义Student类的对象何时相等,或者定义比较它们的方法。
您可以通过让班级学生实施IComparable界面和/或让班级学生覆盖Equals和GetHashCode方法来实现此目的。
另外,如果您有一种比较对象的方法,这将为您提供studentDestinationList
但不在studentsSrcList
中的对象的数量:
var diff = studentDestinationList.Count(x => !studentsSrcList.Contains(x));
答案 2 :(得分:0)