简体   繁体   中英

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 .

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}>();

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>());

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM