比较c#中的两个List <string>()

时间:2015-12-10 00:38:53

标签: c# list

为什么下面的代码 s == p 会返回false?

List<string> s=new List<string>();
s.Add("one");
List<string> p=new List<string>();
p.Add("one");

string result = "";

if (s == p)
{
    result = "unequal";
}
else
{
    result = "equal";

}
     what does this indicates?

1 个答案:

答案 0 :(得分:3)

The == in this case is comparing if the two instances of lists are the same. It's not comparing the contents at all. And since they are not the same instance then they are unequal.

Try using SequenceEqual instead:

List<string> s=new List<string>();
s.Add("one");
List<string> p=new List<string>();
p.Add("one");

string result = "";

if (s.SequenceEqual(p))
{
    result = "equal";
}
else
{
    result = "unequal";
}