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

后端 未结 10 2120
梦如初夏
梦如初夏 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:42

    In C# 3, you can do:

    IList<string> l = new List<string> { "test1", "test2", "test3" };
    

    This uses the new collection initializer syntax in C# 3.

    In C# 2, I would just use your second option.

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

    You can create helper generic, static method to create list:

    internal static class List
    {
        public static List<T> Of<T>(params T[] args)
        {
            return new List<T>(args);
        }
    }
    

    And then usage is very compact:

    List.Of("test1", "test2", "test3")
    
    0 讨论(0)
  • 2021-01-31 13:51

    If you're looking to reduce clutter, consider

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

    This uses two features of C# 3.0: type inference (the var keyword) and the collection initializer for lists.

    Alternatively, if you can make do with an array, this is even shorter (by a small amount):

    var arr = new [] { "foo", "bar" };
    
    0 讨论(0)
  • 2021-01-31 13:51

    A list of values quickly? Or even a list of objects!

    I am just a beginner at the C# language but I like using

    • Hashtable
    • Arraylist
    • Datatable
    • Datasets

    etc.

    There's just too many ways to store items

    0 讨论(0)
提交回复
热议问题