tags:

views:

209

answers:

6

What's the correct C# syntax to do the following using sexier syntax?

string[] arr = ///....
List<string> lst = new List<string>();

foreach (var i in arr) {
   lst.Add(i);
}

I feel like this could be a one liner using something like: arr.Select(x => lst.Add(x));

but I'm not quite bright enough to figure out the right syntax.

+11  A: 
List<string> lst = arr.ToList();

http://msdn.microsoft.com/en-us/library/bb342261.aspx

Daniel A. White
While I appreciate that this is clearly more efficient than any other way of doing it, I was asking the question to better understand the C# syntax.
Armentage
+3  A: 

list.AddRange(arr) ?

chris166
+2  A: 

.Net 2.0:

lst.AddRange(arr);
Meta-Knight
+14  A: 

.ToList() is fine, but to be honest, you don't need LINQ for that:

List<int> list = new List<int>(arr);
Marc Gravell
While I appreciate that this is clearly more efficient than any other way of doing it, I was asking the question to better understand the C# syntax.
Armentage
+1  A: 

You can just do this...

String[] arr = new String[] { "Hello", "Bonjour", "Hola" };

List<String> lst = arr.ToList();

If you are missing the .ToList() method you might need to add using System.Linq; to your code...

Thanks :)

Chalkey
A: 
  string[] arr = new string[] { "a", "b", "c" };
  var lst = new List<string>();
  Array.ForEach(arr, x => lst.Add(x));
Robin
Thanks, this is sort of what I was looking for, though I feel that the Array.ForEach seems a little superfluous. Isn't there something a little bit more generic that can be arbitrarily applied to anything that is Enumerable?
Armentage