Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ/Lambdas to copy a String[] into a List<String>?

Tags:

c#

linq

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.

like image 900
Armentage Avatar asked Nov 27 '22 05:11

Armentage


2 Answers

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

List<int> list = new List<int>(arr);
like image 136
Marc Gravell Avatar answered Dec 19 '22 10:12

Marc Gravell


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

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

like image 42
Daniel A. White Avatar answered Dec 19 '22 10:12

Daniel A. White