0

Lets say I have a string that contains multiple values:

private string serverList = "Server 1, Server 2, Server 3";

Is it possible to add these values into a list? Clearly if I just use List.Add(serverList); I will get all 3 as a single element. What I need is 3 separate elements for serverList.

Randy Levy
  • 22,566
  • 4
  • 68
  • 94
Kyle Dom
  • 1
  • 1

3 Answers3

3

Use the Split method to break your string up into an array

string[] servers = serverList.Split(',');
Jason
  • 86,222
  • 15
  • 131
  • 146
  • 2
    Note that using the single-character `(',')` will return all of the strings with the prepended space - it might be more useful to use `(", ")` – David Dec 30 '14 at 20:51
  • 2
    True, or just trim out whitespace when adding them to the list – Jason Dec 30 '14 at 20:52
3
serverList.Split(',').Select(server => server.Trim()).ToList();
Vikas Gupta
  • 4,455
  • 1
  • 20
  • 40
  • Note that since `Split` is defined with `params` it's completely unnecessary to specify a `new string[]`. Also, this code won't compile - `','` is a `char` and not a `string` because you used single quotes – David Dec 30 '14 at 20:56
  • @Aravol you are right.. I goofed up while making edits. I have corrected it now.. Thanks.. May I suggest that feel free to edit posts, when you see such obvious errors (notepad complied as they call it).. I am sure original author will appreciate it :) – Vikas Gupta Dec 30 '14 at 21:32
0
string serverList = "Server 1,Server 2,Server 3";

List<string> listServers = new List<string>{};

listServers.AddRange(serverList.Split(',')); //  utilize AddRange instead of Add

List.AddRange Method

Vikas Gupta
  • 4,455
  • 1
  • 20
  • 40