473,608 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparing Arrays (Sounds easy but I can't find it!)

Hi Everyone!

I have two Arrays A and B. Both arrays are byte arrays with 7 bytes each.
The contents of array A and B are the same

A = {1, 2, 3, 4, 5, 6, 7};
B = {1, 2, 3, 4, 5, 6, 7};

When I do

if (A == B)
{
dosomething();
}

the system does not think that they are the same...

Does this have something to do with heap and stack? (*shiver*)

How can I compare two arrays?

Thanks for your help!

Mike
Nov 16 '05 #1
18 39981
OK. For predefined value types, the equality operator (==) returns true if
the values of its operands are equal, false otherwise. For _reference_ types
other than string, == returns true, if its two operands refer to the same
_object_. For the string type, == compares the values of the strings...

Still the question remains, how does one compare arrays?
Nov 16 '05 #2
A == B is testing whether object reference A is the same as object reference
B. Since they are different arrays they will be unequal.

A and B are both objects of type Array.

To my knowledge the only way to compare two arrays is to iterate through
them both until you find an element that's unqeual. If you get all the way
through without finding such, they are "equal" in the sense you mean.

Something like:

public bool ArraysEqual(Arr ay a1,Array a2) {

if (a1.Length != a2.Length) {
return false;
}

foreach (int i1 in a1) {

foreach (int i2 in a2) {

if (i1 != i2) {
return false;
}

}

}

return true;
}

Notice that the quick and dirty (and untested) routine above assumes you're
dealing with two integer arrays. This probably gets to the root of why MSFT
hasn't overridden the equals operator for Array to something more generally
useful. Without generics (which will be available in the next release of
..NET) it's difficult to implement an efficient routine to compare arrays
regardless of the type of data they contain.

--Bob

"Mike Bartels" <ne**@news.t-online.de> wrote in message
news:c8******** *****@news.t-online.com...
Hi Everyone!

I have two Arrays A and B. Both arrays are byte arrays with 7 bytes each.
The contents of array A and B are the same

A = {1, 2, 3, 4, 5, 6, 7};
B = {1, 2, 3, 4, 5, 6, 7};

When I do

if (A == B)
{
dosomething();
}

the system does not think that they are the same...

Does this have something to do with heap and stack? (*shiver*)

How can I compare two arrays?

Thanks for your help!

Mike

Nov 16 '05 #3
Mike Bartels <ne**@news.t-online.de> wrote:
OK. For predefined value types, the equality operator (==) returns true if
the values of its operands are equal, false otherwise. For _reference_ types
other than string, == returns true, if its two operands refer to the same
_object_. For the string type, == compares the values of the strings...
Note that it's not just string - it's any type which overrides the ==
operator. This could include some of your own types, and there may well
be other types in the framework which override the equality operator.
Still the question remains, how does one compare arrays?


It's fairly easy to write a method which compares each element in
turn...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
Bob Grommes <bo*@bobgrommes .com> wrote:
A == B is testing whether object reference A is the same as object reference
B. Since they are different arrays they will be unequal.

A and B are both objects of type Array.

To my knowledge the only way to compare two arrays is to iterate through
them both until you find an element that's unqeual. If you get all the way
through without finding such, they are "equal" in the sense you mean.

Something like:

public bool ArraysEqual(Arr ay a1,Array a2) {

if (a1.Length != a2.Length) {
return false;
}

foreach (int i1 in a1) {

foreach (int i2 in a2) {

if (i1 != i2) {
return false;
}

}

}

return true;
}


That won't work - that checks that each element in a2 is equal to *all*
the elements in a1. Instead of the foreach blocks, you want:

for (int i=0; i < a1.Length; i++)
{
if (a1[i] != a2[i])
{
return false;
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
"Jon Skeet [C# MVP]" wrote:
[...]
That won't work - that checks that each element in a2 is equal to *all*
the elements in a1. Instead of the foreach blocks, you want:

for (int i=0; i < a1.Length; i++)
{
if (a1[i] != a2[i])
{
return false;
}
}
[...]


Hi Jon,

that won't work.
'Cannot apply indexing with [] to an expression of type System.Array'
use enumerator instead.

--
Hans-Gerd Zigann - <hg******@web.d e>
..NET Blog @ http://weblogs.netug.de/hgzigann
Nov 16 '05 #6
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Bob Grommes <bo*@bobgrommes .com> wrote:
A == B is testing whether object reference A is the same as object reference B. Since they are different arrays they will be unequal.

A and B are both objects of type Array.

To my knowledge the only way to compare two arrays is to iterate through
them both until you find an element that's unqeual. If you get all the way through without finding such, they are "equal" in the sense you mean.

Something like:

public bool ArraysEqual(Arr ay a1,Array a2) {

if (a1.Length != a2.Length) {
return false;
}

foreach (int i1 in a1) {

foreach (int i2 in a2) {

if (i1 != i2) {
return false;
}

}

}

return true;
}


That won't work - that checks that each element in a2 is equal to *all*
the elements in a1. Instead of the foreach blocks, you want:

for (int i=0; i < a1.Length; i++)
{
if (a1[i] != a2[i])
{
return false;
}
}


This won't find the case where a2.Length is bigger than a1, so you'll fall
out of the loop and not return false.

--
Mabden
Nov 16 '05 #7
Mabden <ma****@sbcglob al.net> wrote:
This won't find the case where a2.Length is bigger than a1, so you'll fall
out of the loop and not return false.


Yes it will - because the if statement at the start (which I wasn't
suggesting should be removed) will catch that case.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
Hans-Gerd Zigann <hg******@web.d e> wrote:
that won't work.
'Cannot apply indexing with [] to an expression of type System.Array'
use enumerator instead.


Ah - cast both to IList then, and it'll be fine. However, it's slightly
worse than I thought, as of course boxed values won't get unboxed to
identical references - we need to call Equals instead. We should also
handle the case where either argument is null...

Here's the full method, as it's getting confusing now:

static bool ArraysEqual (Array a1, Array a2)
{
if (a1==a2)
{
return true;
}

if (a1==null || a2==null)
{
return false;
}

if (a1.Length != a2.Length)
{
return false;
}

IList list1=a1, list2=a2;

for (int i=0; i < a1.Length; i++)
{
if (!Object.Equals (list1[i], list2[i]))
{
return false;
}
}
return true;
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #9
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Hans-Gerd Zigann <hg******@web.d e> wrote:
that won't work.
'Cannot apply indexing with [] to an expression of type System.Array'
use enumerator instead.

This doesn't seem right, I can do the following:

class Test
{
public static bool test(int[]A, int[]B)
{
if (A.Length != B.Length)
return false;
for (int i=0; i < A.Length; i++)
{
if (A[i] != B[i])
return false;
}
return true;
}

static void Main ()
{
bool result;
int[] x= {1,2,3,4,5,6};
int[] y= {1,2,3,4,5,6};
int[] z= {1,2,3,4,6,7};

result = test(x,y);
if (true == result)
System.Console. WriteLine ("Equal!");
else
System.Console. WriteLine ("Not equal!");

result = test(y,z);
if (true == result)
System.Console. WriteLine ("Equal!");
else
System.Console. WriteLine ("Not equal!");

return;
}
}


Ah - cast both to IList then, and it'll be fine. However, it's slightly
worse than I thought, as of course boxed values won't get unboxed to
identical references - we need to call Equals instead. We should also
handle the case where either argument is null...

Doesn't "a1.Length" cover null?


Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1422
by: maddog | last post by:
C/C++ In dev6 we had a profiler tool, I now have dot net 2003 Pro, cost me over £800. But I can't find the profiler anywhere, just wasted the last our searching the docs. Can't see the wood for the trees. There was stuff about a 'Visual Studio Analyzer ' What is it? I would hope that dot net still has a profiler.
6
1259
by: Klaas | last post by:
I want the backgrond of my whole page in gradient. In the source tab I have: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head>
2
2074
by: andrewanderson | last post by:
hi can anyone help me with this prog. cant find the prob why it cant display cout<<"This is the display of your transaction"<<endl; ifstream fobj; //declare input file stream fobj.open("trans.txt"); //open file if(!fobj) //File not opened
1
1924
by: foocc | last post by:
Hi, im trying to convert data reports (.dsr) in vb6 to crystal reports in vb.net. However, I cant seems to find it in my Microsoft Visual Studio 2005 Tools for Office. I've tried going to Project > Add New Item and Solution Explorer > Add > New Item ....but i cant find crystal reports in any of it....The only thing i found is report (.rdlc) Can report(.rdlc) be used to convert data reports in vb6 to vb.net? Or are there any other...
4
2954
by: rnot | last post by:
Hello, I would like to paste data at a cell found by the Selection.Autofilter function. My two first columns hold a "scenario" and "replication" data. I would like upon running a macro to paste certain data into the third column at the same row where the replication and scenario are located. Scen = Application.InputBox("Choose Scenario") Rep = Application.InputBox("Choose Replication") Range("A2:B650000").Select...
0
8071
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8013
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8488
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8360
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6017
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5489
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3977
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
1345
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.