gpt4 book ai didi

c# - 比较两个 List : How to find out difference?

转载 作者:行者123 更新时间:2023-11-30 19:46:35 25 4
gpt4 key购买 nike

我曾经像这样比较列表,但它在测试中返回 false:

Assert.IsTrue(expected.SequenceEquals(actual));

并尝试转换为 json 并且成功了:

Assert.AreEqual(expected.ToJson(), actual.ToJson());

值(value)观似乎是平等的,有什么不同?如何找出列表中的不同之处?

更新:

我的类(class):

public class Department
{
[BsonId]
public ObjectId Id { get; set; }
public string Name { get; set; }

public override string ToString()
{
return Id.ToString();
}
}

最佳答案

如果MyClass工具 IEquatable<MyClass> ,然后试试这个:

expected.Sort(); 
actual.Sort();
if (Enumerable.SequenceEqual(actual, expected)) { ... }

如果它没有实现IEquatable那么您可能会遇到奇怪的行为,因为对象引用将在两个列表中进行比较,而不是它们的字段:

using System;
using System.Collections.Generic;
using System.Linq;

public class MyClassA
{
private int i;
public MyClassA(int i) { this.i = i; }
}

public class MyClassB : IEquatable<MyClassB>
{
private int i;
public MyClassB(int i) { this.i = i; }
public bool Equals(MyClassB other) { return this.i == other.i; }
}

public class Program
{
public static void Main()
{
var actual1 = new List<MyClassA>() { new MyClassA(1), new MyClassA(2), new MyClassA(3) };
var expected1 = new List<MyClassA>() { new MyClassA(1), new MyClassA(2), new MyClassA(3) };
Console.WriteLine(Enumerable.SequenceEqual(actual1, expected1));

var a1 = new MyClassA(1);
var a2 = new MyClassA(2);
var a3 = new MyClassA(3);
var actual2 = new List<MyClassA>() { a1, a2, a3 };
var expected2 = new List<MyClassA>() { a1, a2, a3 };
Console.WriteLine(Enumerable.SequenceEqual(actual2, expected2));

var actual3 = new List<MyClassB>() { new MyClassB(1), new MyClassB(2), new MyClassB(3) };
var expected3 = new List<MyClassB>() { new MyClassB(1), new MyClassB(2), new MyClassB(3) };
Console.WriteLine(Enumerable.SequenceEqual(actual3, expected3));

var actual4 = new List<MyClassB>() { new MyClassB(1), new MyClassB(2), new MyClassB(3) };
var expected4 = new List<MyClassB>() { new MyClassB(3), new MyClassB(2), new MyClassB(1) };
Console.WriteLine(Enumerable.SequenceEqual(actual4, expected4));
}
}

输出:

False
True
True
False

关于c# - 比较两个 List<MyClass> : How to find out difference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8415602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com