我知道以前有人问过同标题的问题,但这是我的情况:
我想比较两个自定义对象列表,它们既不覆盖 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" } };
我试图避免这样的 for:
if(l1.Count != l2.Count)return;
for (int i = 0; i < l1.Count; i++)
{
if(!Compare(l1[i], l2[i]))return;
}
bool comparisonResult = true;
使用 linq,但我想我遗漏了一些东西:
bool comparisonResult = l1.Any(x => l2.Any(y => Compare(x, y)));
这是已经尝试过的方法,但是当列表不相同时它会一直返回 true
。
最佳答案
如果您必须使用 LINQ 并且不想为 Custom
实现 IEqualityComparer
...
假设两个列表的顺序正确,您可以使用 Zip
创建一个新列表,其中每个项目并排排列,有点像 Tuple
。然后,您可以调用该新列表上的 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));
关于c# - 通过指定方法比较两个自定义对象列表 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38400682/