Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用指定的方法C比较两个自定义对象列表#_C#_Linq - Fatal编程技术网

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”

这不会解决列表中出现重复项的情况,因此您可以:

  • 区分列表
  • 内部函数a中的Do,其中和计数等于1

  • 如果您必须使用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));