Mats
Mats

Reputation: 14817

Syntax for initializing a List<T> with existing List<T> objects

is it possible to initialize a List with other List's in C#? Say I've got these to lists:

List<int> set1 = new List<int>() {1, 2, 3};
List<int> set2 = new List<int>() {4, 5, 6};

What I'd like to have is a shorthand for this code:

List<int> fullSet = new List<int>();
fullSet.AddRange(set1);
fullSet.AddRange(set2);

Thanks in advance!

Upvotes: 0

Views: 879

Answers (4)

Jason
Jason

Reputation: 28590

To allow duplicate elements (as in your example):

List<int> fullSet = set1.Concat(set2).ToList();

This can be generalized for more lists, i.e. ...Concat(set3).Concat(set4). If you want to remove duplicate elements (those items that appear in both lists):

List<int> fullSet = set1.Union(set2).ToList();

Upvotes: 8

BFree
BFree

Reputation: 103742

        static void Main(string[] args)
        {
            List<int> set1 = new List<int>() { 1, 2, 3 };
            List<int> set2 = new List<int>() { 4, 5, 6 };

            List<int> set3 = new List<int>(Combine(set1, set2));
        }

        private static IEnumerable<T> Combine<T>(IEnumerable<T> list1, IEnumerable<T> list2)
        {
            foreach (var item in list1)
            {
                yield return item;
            }

            foreach (var item in list2)
            {
                yield return item;
            }
        }

Upvotes: 1

nothrow
nothrow

Reputation: 16168

List<int> fullSet = new List<int>(set1.Union(set2));

may work.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

var fullSet = set1.Union(set2); // returns IEnumerable<int>

If you want List<int> instead of IEnumerable<int> you could do:

List<int> fullSet = new List<int>(set1.Union(set2));

Upvotes: 0

Related Questions