Compare two object as Array;

How to compare two objects which may be is two Arrays.

  var arrayServer = serv as Array;
  var arrayLocal = local as Array;

I don't now why, but I can't use SequenceEqual for arrayServer or arrayLocal .

Upvotes: 0

Views: 162

Answers (3)

w.b
w.b

Reputation: 11228

SequenceEqual is one of LINQ methods, which are implemented as extensions on generic IEnumerable<T>. Array doesn't implement IEnumerable<T>, but you can get generic IEnumerable<T> from it by calling either OfType or Cast:

bool areEqual = arrayLocal.Cast<theType>().SequenceEqual(arrayServer.Cast<theType>());

Upvotes: 0

Wilsu
Wilsu

Reputation: 348

To compare the elements of 2 arrays you can use a loop:

bool itemsEqual = true;
int i = 0;
while(itemsEqual && i < arrayServ.Count)
{
    if(arrayServ[i].Equals(arrayLocal[i])
    {
        i++;
        continue;
    }
    itemsEqual = false;
    return itemsEqual;
}
return itemsEqual;

This will iterate through the serv array and compare the items to the items of local at the same index. If all of them are equal, nothing much will happen and true will be returned. If any comparison returns false, false will be returned. Though using arrays isn't exactly fun.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152566

I can't use SequenceEqual for arrayServer or arrayLocal .

That's because Array does not implement IEnumerable<T> which is necessary for SequenceEqual. Instead of casting to array I would cast to an IEnumerable<T> (with T being the appropriate type of the collection items):

var arrayServer = serv as IEnumerable<{type}>;
var arrayLocal = local as IEnumerable<{type}>;

or use Cast:

var arrayServer = serv.Cast<{type}>();
var arrayLocal = local.Cast<{type}>();

Upvotes: 3

Related Questions