Reputation: 14817
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
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
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
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