问题描述:

I want to have a compare method that takes two objects and return if they are equal or not.

Inside the method I distinguish between different data types to apply the proper comparison method to the objects.

The problem is, I handover two arrays (e.g. int[]) and want to use now SequenceEqual(), so I have to change the objects to some generic sequence/list/array that can apply SequenceEqual() correctly to them.

At the moment I don't now how to change the data type correctly to something generic that does that.

An IEnumerable<object> would have the method SequenceEqual(), but if I do it this way, source and test are null.

public static bool Compare(this object o1, object o2)

{

if (o1 is Array && o2 is Array)

{

// special array handling

IEnumerable<object> source = o1 as IEnumerable<object>;

IEnumerable<object> test = o2 as IEnumerable<object>;

// this fails now, because source and test are null.

return source.SequenceEqual(test);

}

else

{

return o1.Equals(o2);

}

}

Compare() is an Extension method to Object, so I do this to call it:

int[] a = new int[] { 1, 2, 3 };

int[] b = new int[] { 1, 2, 3 };

a.Compare(b);

What do I have to do to treat the two objects, that are Arrays, as arrays so that I can use SequenceEqual()?

网友答案:

Array implements IEnumerable so you can do:

IEnumerable<object> source = ((IEnumerable)o1).Cast<object>();
IEnumerable<object> test = ((IEnumerable)o2).Cast<object>();
网友答案:

Try adding another overload like this:

public static bool Compare<T>(this T[] o1, T[] o2)
{
    return o1.SequenceEqual(o2);
}

to handle arrays.

网友答案:

I think you should cast it first to a array, then convert it to IEnumerable, so the answer is:

public static bool Compare(this object o1, object o2)
{
    if (o1 is Array && o2 is Array)
    {
        // special array handling
        IEnumerable<object> source = (o1 as Array).A();
        IEnumerable<object> test = (o2 as Array).A();

        // this fails now, because source and test are null.
        return source.SequenceEqual(test);
    }
    else
    {
        return o1.Equals(o2);
    }

}
public static IEnumerable<object> A(this Array a)
{
    foreach (var item in a)
    {
        yield return item;
    }
}
相关阅读:
Top