I want to initialize a list with an object and a list of objects in that specific order. Currently, I am doing:
List<MyObject> list = new List<MyObject>();
list.Add(object1); // object1 is type MyObject
list.AddRange(listOfObjects); // listOfObjects is type List<MyObject>
I was hoping to consolidate that into an initialization statement (the syntax is wrong of course):
List<MyObject> newList = new List<MyObject>() { object1, listOfObjects };
Is there a way to do this concisely?
If the order of the elements is not important, you can use:
This works by using the
List<T>constructor which accepts anIEnumerable<T>, then the collection initializer to add the other items. For example, the following:Will print:
Note that the order is different than your original, however, as the individual item is added last.
If the order is important, however, I would personally just build the list, placing in your first object in the initializer, and calling
AddRange:This makes the intention very clear, and avoids construction of temporary items (which would be required using LINQ’s Concat, etc).