Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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

may work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top