-2

Why in the below code s==p returns 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?
Tom Cruise
  • 1,395
  • 11
  • 30
  • 58
  • 4
    Because they're different lists, even if they contain the same information. – Rob Dec 10 '15 at 00:41
  • 1
    You are comparing objects -- this is not the type of comparison you think you are getting. The comparison you are doing only tells you if the two references are the same object. Look at the following post for some examples of how you might accomplish the comparison you intended: http://stackoverflow.com/questions/15612162/compare-the-difference-between-two-liststring – David Tansey Dec 10 '15 at 00:42
  • Yes, what Rob and David said. It looks like you want to compare the actual **values** in the lists instead. http://stackoverflow.com/questions/12795882/quickest-way-to-compare-two-list – Daniel Hakimi Dec 10 '15 at 00:44
  • Actually s == p returns true in your case (was valid with the line p = s;) - it is your resulting string is wrong (should be if (s == p) { result = "equal"; }) – JleruOHeP Dec 10 '15 at 00:47
  • 3
    Why is this question being downvoted? I know it's relatively basic but it seems like a pretty valid logical question. Is there a rule I should know about? – wentimo Dec 10 '15 at 03:09
  • SO should introduce a rule that no downvotes has to be allowed without proper explanation. – user1357872 Dec 10 '15 at 10:32

1 Answers1

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";
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172