Quick way to create a list of values in C#?

后端 未结 10 2119
梦如初夏
梦如初夏 2021-01-31 13:14

I\'m looking for a quick way to create a list of values in C#. In Java I frequently use the snippet below:

List l = Arrays.asList(\"test1\",\"test2         


        
相关标签:
10条回答
  • 2021-01-31 13:32

    You can simplify that line of code slightly in C# by using a collection initialiser.

    var lst = new List<string> {"test1","test2","test3"};
    
    0 讨论(0)
  • 2021-01-31 13:32

    If you want to create a typed list with values, here's the syntax.

    Assuming a class of Student like

    public class Student {
       public int StudentID { get; set; }
       public string StudentName { get; set; }
     }   
    

    You can make a list like this:

    IList<Student> studentList = new List<Student>() { 
                    new Student(){ StudentID=1, StudentName="Bill"},
                    new Student(){ StudentID=2, StudentName="Steve"},
                    new Student(){ StudentID=3, StudentName="Ram"},
                    new Student(){ StudentID=1, StudentName="Moin"}
                };
    
    0 讨论(0)
  • You can drop the new string[] part:

    List<string> values = new List<string> { "one", "two", "three" };
    
    0 讨论(0)
  • 2021-01-31 13:36
    IList<string> list = new List<string> {"test1", "test2", "test3"}
    
    0 讨论(0)
  • 2021-01-31 13:38

    You can do that with

    var list = new List<string>{ "foo", "bar" };
    

    Here are some other common instantiations of other common Data Structures:

    Dictionary

    var dictionary = new Dictionary<string, string> 
    {
        { "texas",   "TX" },
        { "utah",    "UT" },
        { "florida", "FL" }
    };
    

    Array list

    var array = new string[] { "foo", "bar" };
    

    Queue

    var queque = new Queue<int>(new[] { 1, 2, 3 });
    

    Stack

    var queque = new Stack<int>(new[] { 1, 2, 3 });
    

    As you can see for the majority of cases it is merely adding the values in curly braces, or instantiating a new array followed by curly braces and values.

    0 讨论(0)
  • 2021-01-31 13:40

    Check out C# 3.0's Collection Initializers.

    var list = new List<string> { "test1", "test2", "test3" };
    
    0 讨论(0)
提交回复
热议问题