[c#] How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

I am writing my testcode and I do not want wo write:

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");

I would love to write

List<string> nameslist = new List<string>({"one", "two", "three"});

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

This question is related to c# list collections initialization

The answer is


var list = new List<string> { "One", "Two", "Three" };

Essentially the syntax is:

new List<Type> { Instance1, Instance2, Instance3 };

Which is translated by the compiler as

List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");

Change the code to

List<string> nameslist = new List<string> {"one", "two", "three"};

or

List<string> nameslist = new List<string>(new[] {"one", "two", "three"});

Just lose the parenthesis:

var nameslist = new List<string> { "one", "two", "three" };

List<string> nameslist = new List<string> {"one", "two", "three"} ?

This is one way.

List<int> list = new List<int>{ 1, 2, 3, 4, 5 };

This is another way.

List<int> list2 = new List<int>();

list2.Add(1);

list2.Add(2);

Same goes with strings.

Eg:

List<string> list3 = new List<string> { "Hello", "World" };

Remove the parentheses:

List<string> nameslist = new List<string> {"one", "two", "three"};

Posting this answer for folks wanting to initialize list with POCOs and also coz this is the first thing that pops up in search but all answers only for list of type string.

You can do this two ways one is directly setting the property by setter assignment or much cleaner by creating a constructor that takes in params and sets the properties.

class MObject {        
        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> { new MObject{ PASCode = 111, Org="Oracle" }, new MObject{ PASCode = 444, Org="MS"} };

OR by parameterized constructor

class MObject {
        public MObject(int code, string org)
        {
            Code = code;
            Org = org;
        }

        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> {new MObject( 111, "Oracle" ), new MObject(222,"SAP")};


        

It depends which version of C# you're using, from version 3.0 onwards you can use...

List<string> nameslist = new List<string> { "one", "two", "three" };

I think this will work for int, long and string values.

List<int> list = new List<int>(new int[]{ 2, 3, 7 });


var animals = new List<string>() { "bird", "dog" };

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to initialization

"error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to declare an ArrayList with values? Initialize array of strings Initializing a dictionary in python with a key value and no corresponding values Declare and Initialize String Array in VBA VBA (Excel) Initialize Entire Array without Looping Default values and initialization in Java Initializing array of structures C char array initialization