If the order of the elements is not important, you can use:
List<MyObject> newList = new List<MyObject>(listOfObjects) { object1 };
This works by using the List<T>
constructor which accepts an IEnumerable<T>
, then the collection initializer to add the other items. For example, the following:
static void Main()
{
int test = 2;
List<int> test2 = new List<int>() { 3, 4, 5 };
List<int> test3 = new List<int>(test2) { test };
foreach (var t in test3) Console.WriteLine(t);
Console.ReadKey();
}
Will print:
3
4
5
2
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
:
List<MyObject> newList = new List<MyObject> { object1 };
newList.AddRange(listOfObjects);
This makes the intention very clear, and avoids construction of temporary items (which would be required using LINQ’s Concat, etc).