user2609410
user2609410

Reputation: 319

C# Union two lists of objects:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<A> l = new List<A>();
        l.Add(new A("q"));

        l.Union(new[] {new A("w"), new A("E")}, new AComparer());

        Console.Write(l.Count);
    }
}

public class A
{
    public String b;

    public A(String x)
    {
        b = x;
    }
}

public class AComparer : IEqualityComparer<A>
{
    public bool Equals(A x, A y)
    {
        return x != null && y != null && x.b.Equals(y.b);
    }

    public int GetHashCode(A obj)
    {
        return 0;
    }
}

Unable to figure out how to make the list size go 3? I tried looking up https://msdn.microsoft.com/en-us/library/bb341731(v=vs.110).aspx but unable to figure out if I'm missing anything

Upvotes: 1

Views: 15611

Answers (1)

Adam Brown
Adam Brown

Reputation: 1729

Union isn't a member of list, but is an extension on IEnumerable - part of Linq. This means it's pure and doesn't affect the state of the list, but returns a new Enumeration. So you could do

l = l.Union(otherL).ToList();

Upvotes: 9

Related Questions