我想比较两个集合(在C#中),但我不确定有效实现它的最佳方法.
我已经阅读了关于Enumerable.SequenceEqual的其他帖子,但这并不是我正在寻找的.
在我的情况下,如果它们都包含相同的项目(无论顺序),则两个集合将是相等的.
例:
collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};
collection1 == collection2; // true
Run Code Online (Sandbox Code Playgroud)
我通常做的是遍历一个集合中的每个项目,看看它是否存在于另一个集合中,然后循环遍历另一个集合的每个项目,看它是否存在于第一个集合中.(我首先比较长度).
if (collection1.Count != collection2.Count)
return false; // the collections are not equal
foreach (Item item in collection1)
{
if (!collection2.Contains(item))
return false; // the collections are not equal
}
foreach (Item item in collection2)
{
if (!collection1.Contains(item))
return false; // the collections are not equal
}
return true; // the collections are equal
Run Code Online (Sandbox Code Playgroud)
但是,这并不完全正确,并且它可能不是比较两个集合的最有效方法.
我能想到的一个例子是错误的:
collection1 …Run Code Online (Sandbox Code Playgroud) 我曾经比较像这样的列表,但它在测试中返回false:
Assert.IsTrue(expected.SequenceEquals(actual));
Run Code Online (Sandbox Code Playgroud)
并尝试转换为json,它工作:
Assert.AreEqual(expected.ToJson(), actual.ToJson());
Run Code Online (Sandbox Code Playgroud)
价值似乎是平等的,可能会有什么不同?如何找出列表中的不同之处?
更新:
我的课:
public class Department
{
[BsonId]
public ObjectId Id { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Id.ToString();
}
}
Run Code Online (Sandbox Code Playgroud) 我有 2 个字符串,例如“abcdefg”“bcagfed”我想编写一个方法来确定这两个字符串相等
*排序或未排序并不重要。在我的示例中,上面的字符串是相等的。
一个答案是:在检查相等性之前,对它们进行排序,然后可以轻松检查相等性,但这不是最快的方法