c# - 通过指定方法比较两个自定义对象列表 C#

标签 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)
{
    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/

相关文章:

c# - 在工厂中使用通用接口(interface)时推断类型

c# - 如何在 XML 配置中声明 Unity InjectionFactory

c# - IList 麻烦。固定尺寸?

c# - 16 位 11025 单声道 WAVE 数据中的一个样本值

c# - 如何在不使用基本查询的情况下在一项操作中解析多个 linq 查询?

c# - 如何扩展类并覆盖来自接口(interface)的方法?

c# - 使用 LINQ 查询动态数据

c# - 使用 LINQ 做我需要做的事情的更好方法?

c# - 嵌套 Linq 比 foreach 循环更快吗?

c# - 如何在 C# 中使用 linq 获取多级深度订单项?