views:

156

answers:

4

Hello,

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!

A: 
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));
Darin Dimitrov
A: 
List<int> fullSet = new List<int>(set1.Union(set2));

may work.

Yossarian
+1  A: 
        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;
            }
        }
BFree
That's just Enumerable.Concat of course...
Jon Skeet
I'm not sure why when I first answered the question I thought the OP was looking for a 2.0 solution.... Not sure where I got that from.....
BFree
+8  A: 

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