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

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

    If you're looking to reduce clutter, consider

    var lst = new List { "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" };
    

提交回复
热议问题