2

I have 3 List<> objects.

List<T> listA = new List<t>();
List<T> listB = new List<t>();
List<T> listC = new List<t>();

I need to unite listA and ListB and assign it to ListC:

List<T> listC = new ListA +ListB;

My question is how to implement it?

Michael
  • 13,950
  • 57
  • 145
  • 288

6 Answers6

7
    List<int> A = new List<int>();
    A.Add(1);
    A.Add(2);
    List<int> B = new List<int>();
    B.Add(3);
    B.Add(4);

    List<int> C = new List<int>();

    C = A.Union<int>(B).ToList<int>();
Mohsen Afshin
  • 13,273
  • 10
  • 65
  • 90
  • 1
    It wasn't specified, but `Union` would remove duplicate entries if they exist. If @Michael wants to keep duplicates, use `Concat` instead. – Chris Sinclair Oct 13 '12 at 14:27
  • You should have mentioned that OP needs to implement an `EqualityComparer`(like [here](http://stackoverflow.com/a/12873969/284240)) if it's a custom type. Otherwise he would compare reference types by reference instead by equality. – Tim Schmelter Oct 14 '12 at 10:17
5

Use AddRange:

List<T> listA = new List<t>();
List<T> listB = new List<t>();
List<T> listC = new List<t>();

listC.AddRange(listA);
listC.AddRange(listB);
Leri
  • 12,367
  • 7
  • 43
  • 60
4

Try AddRange() this:-

    listC.AddRange(listA);
    listC.AddRange(listB);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
3

Kinda depends on your requirements, but might be as easy as

listC.AddRange(listA);
listC.AddRange(listB);
iamkrillin
  • 6,798
  • 1
  • 24
  • 51
2
listC.AddRange(listA);
listC.AddRange(listB);
Lior
  • 5,841
  • 9
  • 32
  • 46
2

Either use AddRange as others have already mentioned or , if you want to union both as mentioned, you need to provide a IEqualityComparer<T> and use Enumerable.Union:

List<Foo> third = first.Union(second, new FooComparer()).ToList();

Here's an examplary implementation:

public class FooComparer : IEqualityComparer<Foo>
{
    public bool Equals(Foo x, Foo y)
    {
        return x.Id == y.Id; // assuming that there's a value type like ID as key
    }

    public int GetHashCode(Foo obj)
    {
        return obj.Id.GetHashCode();
    }
}

Union returns only unique values.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939