How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)
Asked Answered
R

10

144

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"?

Reluctance answered 14/12, 2010 at 10:31 Comment(0)
A
225
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");
Annotate answered 14/12, 2010 at 10:33 Comment(6)
I like this no-parentheses method, what c# version did that start with?Unruffled
It's not quite translated into that, at least not in general. The assignment to the variable happens after all the Add calls have been made - it's as if it uses a temporary variable, with list = tmp; at the end. This can be important if you're reassigning a variable's value.Mammiemammiferous
Automatic Properties and Object Initialisers were introduced with .NET 3 I believe, it's the same Framework version, just an updated compiler to support LINQ.Annotate
@Jon, Cheers, I never knew that part. :DAnnotate
@Jon Skeet : "...This can be important if you're reassigning a variable's value." can you explain a bit more on this remark?Scopula
@Scopula Consider: list = new List<string> { list[1], list[2], list[0] }; - you don't want list replaced with an empty List<string> before the elements are added.Sensorimotor
D
22

Change the code to

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

or

List<string> nameslist = new List<string>(new[] {"one", "two", "three"});
Dispersant answered 14/12, 2010 at 10:32 Comment(1)
what is the purpose of using the second line " List<string> nameslist = new List<string>(new[] {"one", "two", "three"}); " when can we use it ? Also what is meaning of "new[] {...} " in the second syntax ?why new keyword is used along with the parenthesis [] ???Scopula
A
7

Just lose the parenthesis:

var nameslist = new List<string> { "one", "two", "three" };
Acetamide answered 14/12, 2010 at 10:36 Comment(1)
Oops, look like five people beat me to it.Acetamide
V
7

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")};


        
Vamoose answered 22/2, 2021 at 10:11 Comment(0)
E
4

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" };
Erythrocyte answered 10/8, 2020 at 21:42 Comment(0)
T
3
List<string> nameslist = new List<string> {"one", "two", "three"} ?
Thiol answered 14/12, 2010 at 10:32 Comment(0)
H
3

Remove the parentheses:

List<string> nameslist = new List<string> {"one", "two", "three"};
Heel answered 14/12, 2010 at 10:33 Comment(0)
A
3

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" };
Airlie answered 14/12, 2010 at 10:34 Comment(0)
T
3

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" };
Tense answered 3/9, 2019 at 15:10 Comment(0)
E
2

C# 12 (.NET 8+) way is:

List<string> list = ["One", "Two", "Three"];

though don't use var with it, it needs to know the type since the new collection literals can be used for any kind of collection.

Source: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12#collection-expressions

Evidence answered 28/11, 2023 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.