Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

like image 806
RollerCosta Avatar asked Dec 28 '22 09:12

RollerCosta


2 Answers

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.

like image 105
Adam Houldsworth Avatar answered Dec 30 '22 11:12

Adam Houldsworth


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.

like image 29
Daniel Mošmondor Avatar answered Dec 30 '22 09:12

Daniel Mošmondor