Question

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

Was it helpful?

Solution

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

var myList = new List<string>(myString.Split(','));

OTHER TIPS

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();
string[] strs = "Hello,You".Split(',');
ArrayList al = new ArrayList();
al.AddRange(strs);

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(','));

protected void Button1_Click(object sender, EventArgs e) {

            TextBox1.Text = "Nitin Luhar";
            Array name=TextBox1.Text.Split(' ');
            foreach (string item in name)
            {
                for (int i = 0; i < item.Length; i++)
                {
                    if (i == 0)
                    {
                        Label1.Text = name.GetValue(0).ToString();
                    }
                    if (i == 1)
                    {
                        Label2.Text = name.GetValue(1).ToString();
                    }
                    if (i == 2)
                    {
                        Label3.Text = name.GetValue(2).ToString();
                    }


                }
            }


} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top