RollerCosta
RollerCosta

Reputation: 5186

How to Convert an ArrayList to string C#

ArrayList arr = new ArrayList();
string abc =

What should I do to convert arraylist to a string such as abc = arr;

Updated QuestOther consideration from which i can complete my work is concatination of string(need help in that manner ). suppose i have a
string s="abcdefghi.."
by applying foreach loop on it and getting char by matching some condition and concatinating every char value in some insatnce variable of string type
i.e string subString=+;
Something like this
string tem = string.Empty; string temp =string.Empty; temp = string.Concat(tem,temp);

Upvotes: 5

Views: 29943

Answers (3)

pnps_edge
pnps_edge

Reputation: 32

Personally and for memory preservation I’ll do for a concatenation:

        System.Collections.ArrayList Collect = new System.Collections.ArrayList();
        string temporary = string.Empty;
        Collect.Add("Entry1");
        Collect.Add("Entry2");
        Collect.Add("Entry3");

        foreach (String var in Collect)
        {
            temporary = temporary + var.ToString();  
        }
        textBox1.Text = temporary;

Upvotes: 0

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

Using a little linq and making the assumption that your ArrayList contains string types:

using System.Linq;

var strings = new ArrayList().Cast<string>().ToArray();

var theString = string.Join(" ", strings);

Further reading:

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

For converting other types to string:

var strings = from object o in myArrayList
              select o.ToString();

var theString = string.Join(" ", strings.ToArray());

The first argument to the Join method is the separator, I chose whitespace. It sounds like your chars should all contribute without a separator, so use "" or string.Empty instead.

Update: if you want to concatenate a small number of strings, the += operator will suffice:

var myString = "a";
myString += "b"; // Will equal "ab";

However, if you are planning on concatenating an indeterminate number of strings in a tight loop, use the StringBuilder:

using System.Text;

var sb = new StringBuilder();

for (int i = 0; i < 10; i++)
{
    sb.Append("a");
}

var myString = sb.ToString();

This avoids the cost of lots of string creations due to the immutability of strings.

Upvotes: 9

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

Look into string.Join(), the opposite of string.Split()

You'll also need to convert your arr to string[], I guess that ToArray() will help you do that.

Upvotes: 2

Related Questions