我知道以前曾问过具有相同标题的问题,但这是我的情况:
我想比较两个不覆盖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" } };
我试图避免这样的:
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并且不想实现IEqualityComparer
for Custom
...
假设两个列表的顺序正确,则可以利用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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句