0

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!

1
  • Are you talking of .NET 2/3, or 3.5? Most of the solutions here are for 3.5 only. Commented Sep 10, 2009 at 12:05

4 Answers 4

8

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();
Sign up to request clarification or add additional context in comments.

Comments

1
        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;
            }
        }

1 Comment

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.....
0
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));

Comments

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

may work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.