views:

75

answers:

2

I want to combine two array's, excluding duplicates. I am using a custom class:

public class ArcContact : IEquatable<ArcContact>
{
    public String Text;

    public Boolean Equals(ArcContact other)
    {
        if (Object.ReferenceEquals(other, null)) return false;
        if (Object.ReferenceEquals(this, other)) return true;
        return Text.Equals(other.Text);
    }
    public override Int32 GetHashCode()
    {
        return Text == null ? 0 : Text.GetHashCode();
    }
}

I implemented and the needed IEquatable interface as mentioned in this msdn section. I only want to check the Text property of the ArcContact class and make sure an Array of ArcContact have an unique Text.

Here I pasted the code that I use, as you can see I have method with two parameters, array's to combine and below that the code I got from the previous mentioned msdn section.

internal static class ArcBizz
{
    internal static ArcContact[] MergeDuplicateContacts(ArcContact[] contacts1, ArcContact[] contacts2)
    {
        return (ArcContact[])contacts1.Union(contacts2);
    }
    internal static IEnumerable<T> Union<T>(this IEnumerable<T> a, IEnumerable<T> b);
}

What am I doing wrong?

+1  A: 

The result of the Union is not an array, it's an IEnumerable. You have to use ToArray extension method:

return contacts1.Union(contacts2).ToArray();
Iravanchi
That solves the casting problem. The main problem is the last piece of code. The internal static IEnumerable: I have to put it there right? Because I get an error on that.
D. Veloper
Well, it seems you got your answer while I was off the net :)
Iravanchi
A: 

I would assume you get an InvalidCastException due to:

return (ArcContact[])contacts1.Union(contacts2);

It should be

return contacts1.Union(contacts2).ToArray();

Also, I am not sure what the following is doing in your code:

internal static IEnumerable<T> Union<T>(this IEnumerable<T> a, IEnumerable<T> b);
leppie
Casting solved, thanks.That last piece of code. If I don't put it there how can I use the Union ??? Am I making a n00b error here?
D. Veloper
@D. Veloper: I suggest you simply remove that line, as it should not even compile!
leppie
It worked, thanks! I put it there because I couldn't use .Union in intellisense, I didn't add System.Linq. >_<
D. Veloper