C# 使用指定的方法C比较两个自定义对象列表#
我知道以前有人问过同样标题的问题,但我的情况是: 我想比较两个自定义对象列表,它们既不覆盖C# 使用指定的方法C比较两个自定义对象列表#,c#,linq,C#,Linq,我知道以前有人问过同样标题的问题,但我的情况是: 我想比较两个自定义对象列表,它们既不覆盖Equals,也不实现IEqualityComparer,但我想将它们与静态比较方法进行比较,如: public class Custom { public string Prop1 { get; set; } public string Prop2 { get; set; } } public static bool Compare(Custom A, Custom B) { r
Equals
,也不实现IEqualityComparer
,但我想将它们与静态比较方法进行比较,如:
public class Custom
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
public static bool Compare(Custom A, Custom B)
{
return A.Prop1 == B.Prop1 && A.Prop2 == B.Prop2;
}
假设列表中的元素顺序相同:
List<Custom> l1 = new List<Custom> {new Custom { Prop1 = "A", Prop2 = "B"}, new Custom { Prop1 = "A", Prop2 = "B" } };
List<Custom> l2 = new List<Custom> { new Custom { Prop1 = "A", Prop2 = "B" }, new Custom { Prop1 = "A", Prop2 = "b" } };
这是我们尝试过的,但当列表不相同时,它会不断返回
true
。您可以使用All
bool comparisonResult = l1.All(x => l2.Any(y => Compare(x, y)));
只有当l1中的所有项都匹配内部条件(即它们存在于l2中)时,才会返回true。这是一种更容易阅读的方法,可以两次应用“not”
这不会解决列表中出现重复项的情况,因此您可以:
如果您必须使用LINQ并且不想为
自定义实现IEqualityComparer
假设这两个列表的顺序正确,您可以使用创建一个新列表,每个项目并排显示,有点像元组。然后,您可以调用该新列表中的All来调用静态Compare
方法:
List<Custom> l1 = new List<Custom> {new Custom { Prop1 = "A", Prop2 = "B"}, new Custom { Prop1 = "A", Prop2 = "B" } };
List<Custom> l2 = new List<Custom> { new Custom { Prop1 = "A", Prop2 = "B" }, new Custom { Prop1 = "A", Prop2 = "b" } };
bool comparisonResult = l1.Zip(l2, (x, y) => new { x, y }).All(z => Compare(z.x, z.y));
List l1=new List{new Custom{Prop1=“A”,Prop2=“B”},new Custom{Prop1=“A”,Prop2=“B”};
列表l2=新列表{new Custom{Prop1=“A”,Prop2=“B”},新Custom{Prop1=“A”,Prop2=“B”};
bool comparisonResult=l1.Zip(l2,(x,y)=>new{x,y});
我刚刚测试了您的答案,因为它对我来说似乎很有趣,但对于不同的列表,它不起作用,仍然返回true。但我无法解释为什么,在这种情况下,逻辑似乎很好
bool comparisonResult = l1.All(x => l2.Any(y => Compare(x, y)));
List<Custom> l1 = new List<Custom> {new Custom { Prop1 = "A", Prop2 = "B"}, new Custom { Prop1 = "A", Prop2 = "B" } };
List<Custom> l2 = new List<Custom> { new Custom { Prop1 = "A", Prop2 = "B" }, new Custom { Prop1 = "A", Prop2 = "b" } };
bool comparisonResult = l1.Zip(l2, (x, y) => new { x, y }).All(z => Compare(z.x, z.y));