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
2009-01-20 00:00:13
er, List<string> stringList = new List<string>(myString.Split(','));you beat me to the punch! just fix your variable declaration ;)
TJB
2009-01-20 00:01:56
+1
A:
string[] strs = "Hello,You".Split(',');
ArrayList al = new ArrayList();
al.AddRange(strs);
consultutah
2009-01-20 00:05:06
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
2009-01-20 00:07:22
+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
2009-01-20 00:12:39
Seems like a bit much for an already built in mechanism. Gotta be careful with those extension methods...
Ed Swangren
2009-01-20 00:15:06
@Ed, really? What built-in mechanism exists to convert any IEnumerable to an ArrayList.
JaredPar
2009-01-20 00:16:10
@Atomiton, the questioner asked for ArrayList. Converting to List<object> is fairly easy though. enumerable.Cast<object>.ToList();
JaredPar
2009-01-20 00:21:49
@Jared: The ArrayList constructor will take an ICollection, which is implemented by arrays.
Ed Swangren
2009-01-20 01:12:44
@Jared: But the OP asked..."how can I put the resulting string[] into an ArrayList"
Ed Swangren
2009-01-20 08:38:48
@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
2009-01-20 14:16:17
@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
2009-01-20 17:53:50