【问题标题】:C# List not comparing with equals operatorC# 列表不与等号运算符比较
【发布时间】:2017-05-19 09:27:48
【问题描述】:

我正在比较 C# 中的两个列表。这是基本代码

List<string> expectedTabs = new List<string>() { "Batch", "Card Services", "ReportingXXXXX" };

List<string> actualTabs = new List<string>() { "Batch", "Card Services", "Reporting" };

string [] text = new string[actualTabs.Count];

int i = 0;

foreach (IWebElement element in actualTabs)
{
     text[i++] = element;
     Console.WriteLine("Tab Text : " + text[i - 1]);
}

for(int x = 0; x < actualTabs.Count; x++)
{
    Assert.IsTrue(expectedTabs.Count == actualTabs.Count); //this gives equal count
    Console.WriteLine(expectedTabs[x] + " :: " + actualTabs[x]);

    expectedTabs[x].Equals(actualTabs[x]); //Gives wrong result here

    Console.WriteLine(expectedTabs.GetType()); //returns type as collection.list
}

现在,当比较两个列表中的最后一个元素 [ReportingXXXXX and Reporting] 时,equal 应该返回 false,但它只是给出相等的结果。我不确定我是否需要在这里使用其他东西。

【问题讨论】:

  • 你是怎么检查的?您不会将 Equals 的结果分配给任何变量。只是在调试器中?
  • 加上控制台输出会容易一些
  • 我想你的意思是改用Assert.Equals ( expectedTabs[x],(actualTabs[x]);
  • expectedTabs[x].Equals(actualTabs[x]); 行给出了正确的结果。在调试器中检查自己。你能告诉更多你想要达到的目标吗?可能有几种方法可以实现结果。
  • 测试了你的代码,它在我的机器上运行正常。 expectedTabs[x].Equals(actualTabs[x])ReportingXXXXX :: Reporting 生成 false。此外,您填写text 的那个块似乎无关紧要(编辑1:错误,actualTabs 没有任何IWebElement,所以我在没有那部分的情况下进行了测试)。请提供Minimal, Complete, and Verifiable example。编辑 2:你有没有问过问题?

标签: c# list collections


【解决方案1】:

将您的代码减少到我认为的相关位...

var expectedTabs = new List<string>() { "Batch", "Card Services", "ReportingXXXXX" };
var actualTabs = new List<string>() { "Batch", "Card Services", "Reporting" };
for (var x = 0; x < actualTabs.Count; x++)
{
   var equal = expectedTabs[x].Equals(actualTabs[x]); //Gives wrong result here
   Console.WriteLine(equal);
}

这会产生

True
True
False

您在哪里看到错误的结果?

您的代码/比较工作正常。

【讨论】:

  • 这似乎不是一个答案。
猜你喜欢
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2020-12-10
  • 2016-12-31
  • 2012-10-17
相关资源
最近更新 更多