Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize list with both a single object and another list of objects

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?

like image 434
Joe W Avatar asked Nov 06 '12 18:11

Joe W


People also ask

What is collection initializers in C#?

Collection initializers let you specify one or more element initializers when you initialize a collection type that implements IEnumerable and has Add with the appropriate signature as an instance method or an extension method. The element initializers can be a simple value, an expression, or an object initializer.

How do you initialize a list in Python?

To initialize a list in Python assign one with square brackets, initialize with the list() function, create an empty list with multiplication, or use a list comprehension. The most common way to declare a list in Python is to use square brackets.


2 Answers

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

like image 150
Reed Copsey Avatar answered Sep 16 '22 19:09

Reed Copsey


I think the best you can do is:

List<MyObject> newList = new[] { object1 }.Concat(listOfObjects).ToList(); 
like image 40
Lee Avatar answered Sep 18 '22 19:09

Lee