English 中文(简体)
List.AddRange inline declaration
原标题:

This may seem an easy question, but not to me, also a search has led to nothing. Up until now the only .net programming I have done is with Delphi Prism. With Prism I can do things like:

var l := new List<String>([ A , B , C ]);

or

var l := new List<String>;
l.AddRange([ A , B , C ];

but can I do a similar thing in C#, or do I have to do it like:

var a = new String[] {"A","B","C"};
var l = new List<String>(a);
最佳回答
 var l=new List<String>() {"A","B","C"};  

this will work

问题回答

collection initializer:

var list = new List<string>
{
    "A",
    "B",
    "C"
};

or correct ctor (mixed with collection initializer):

var list = new List<string>(new [] { "A", "B", "C" });
  • msdn for ctor infos
  • msdn for collection initializer

You can use Collection Initializers to achieve desired result.

As mentioned above, use collection initializers. In addition, if you are looking to convert from string[] to List , you can use the ToList() extension method in the System.Linq namespace like so:

string[] s = { "3", "4", "4"};
List<string> z = s.ToList();




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签