views:

2922

answers:

4

C#, a String's Split() method, how can I put the resulting string[] into an ArrayList or Stack?

+16  A: 

You can initialize a List with an array (or any other object that implements IEnumerable). You should prefer the strongly typed List over ArrayList.

List<string> myList = new List<string>(myString.Split(','));
Ed Swangren
er, List<string> stringList = new List<string>(myString.Split(','));you beat me to the punch! just fix your variable declaration ;)
TJB
+1  A: 
string[] strs = "Hello,You".Split(',');
ArrayList al = new ArrayList();
al.AddRange(strs);
consultutah
I would not recommend using ArrayList anymore.
Ed Swangren
Though that is what he asked for.
Ed Swangren
A: 

Or if you insist on an ArrayList or Stack

string myString = "1,2,3,4,5";
ArrayList al = new ArrayList(myString.Split(','));
Stack st = new Stack(myString.Split(','));
johnc
+4  A: 

If you want a re-usable method, you could write an extension method.

public static ArrayList ToArrayList(this IEnumerable enumerable) {  
  var list = new ArrayList;
  for ( var cur in enumerable ) {
    list.Add(cur);
  }
  return list;
}

public static Stack ToStack(this IEnumerable enumerable) {
  return new Stack(enumerable.ToArrayList());
}

var list = "hello wolrld".Split(' ').ToArrayList();
JaredPar
Seems like a bit much for an already built in mechanism. Gotta be careful with those extension methods...
Ed Swangren
Extension methods are the antichrist, but I love them all the same
johnc
@Ed, really? What built-in mechanism exists to convert any IEnumerable to an ArrayList.
JaredPar
Why not convert to a List<Object>
Atømix
@Atomiton, the questioner asked for ArrayList. Converting to List<object> is fairly easy though. enumerable.Cast<object>.ToList();
JaredPar
@Jared: The ArrayList constructor will take an ICollection, which is implemented by arrays.
Ed Swangren
@Ed, my solution is for IEnumerable, not ICollection.
JaredPar
@Jared: But the OP asked..."how can I put the resulting string[] into an ArrayList"
Ed Swangren
@Ed, and I offered a more general solution. It's possible to offer array or ICollection overloads of these functions (or simply try cast the result to an ICollection as most LINQ functions do). Either way, given that the BCL has many of these methods, I don't believe it's overkill
JaredPar
@Jared: You're right, I wouldn't say it was overkill either, just a bit more than needed to solve the OP's problem.
Ed Swangren