0

I am new to C# and just comparing two arrays... both arrays should be equal, as their values are same, but result is always false... not sure why.

char[] arOne =  { 'a', 'b', 'c', '\u0000' };
char[] arTwo = new char[] { 'a', 'b', 'c', '\u0000' };
Console.WriteLine(" Two arrays are equal ? ...{0}", (arOne == arTwo) ? "true" : "false");
2

5 Answers 5

5

Try and use this

Enumerable.SequenceEqual Method (IEnumerable, IEnumerable)

bool areEqual = arOne.SequenceEqual(arTwo);

What you are doing is comparing object references and not the actual contents of the collections.

Sign up to request clarification or add additional context in comments.

Comments

3

Use this code:

Console.WriteLine("Two arrays are equal? ...{0}", arOne.Intersect(arTwo).Any() ? "true" : "false");

1 Comment

it will not check if tables are the same, it will return true to {0} and {0,1}
3

The == operator just compares the references, if they are not the same it returns false. You could use SequenceEqual:

bool bothSameChars = arOne.SequenceEqual(arTwo);

SequenceEqualtakes also the order into account, if that doesn't matter you could use HashSet<Char> and it's SetEquals method which is very efficient:

HashSet<Char> charset1 = new HashSet<Char>(arOne);
HashSet<Char> charset2 = new HashSet<Char>(arTwo);
bothSameChars = charset1.SetEquals(charset2);

Comments

0

Consider the following Code...

Console.WriteLine(" Two arrays are equal ? ...{0}", Enumerable.SequenceEqual(arOne, arTwo) ? "true" : "false");

Good Luck!

Comments

0

You are currently checking the REFERENCE to two objects and check if those are equal, which they obviously are not. What you want to do is check if their CONTENT AND SEQUENCE are equal, for which they invented the awesome function .SequenceEqual(). Your code will be something like

char[] arOne = { 'a', 'b', 'c', '\u0000' };
char[] arTwo = new char[] { 'a', b', 'c', '\u0000' };
Console.WriteLine(" Two arrays are equal ? ... {0}", (arOne.SequenceEqual(arTwo)));

Because SequenceEqual() already returns a boolean, you don't even have to add the ? "true" : false" anymore.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.