开发者

Can't seem to get .Union to work (merging 2 array's together, exclude duplicates)

开发者 https://www.devze.com 2022-12-25 05:31 出处:网络
I want to combine two array\'s, excluding duplicates. I am using a custom class: public class ArcContact : IEquatable<ArcContact>

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.ReferenceEq开发者_如何学JAVAuals(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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消