How can I add to an array which is in a foreach loop.
pseudo example
String[] mylist;
foreach ( ipadress ip in list )
{
// I want to add to array ip.ToString();
}
// then put my list to a textbox
5 Answers 5
If you are using linq try this instead :
String[] mylist = list.Select(I => Convert.ToString(I.ip)).ToArray();
Comments
First of all, if this is a homework problem, it should really be tagged as such.
Anyway, assuming you have complete control of the string[] you are passing values to, and assuming your ipaddress class has .ToString() overloaded to give you back some intelligent information:
string[] myList = new string[list.Count];
int i = 0;
foreach (IPAddress ip in list)
{
myList[i++] = ip.ToString();
}
Although I have to question why you are going back and forth between arrays and list objects to begin with.
6 Comments
Quick and short:
String[] myList;
List<int> intList = new List<int> { 1, 2, 3, 4 };
myList = intList.ConvertAll<String>(p => p.ToString()).ToArray<String>();
Comments
Figured it out...new to programming.., thanks to all. I used same code that tharindlaksh posted.
this is how it looks:
string[] all ;
int i = 0;
foreach (IPAddres ip in host.AddressList)
{
all[i] = ip.ToString();
i++;
}
textBoxMain.Text = all[0] + "\n" + all[1] + \n" + all[2] + "\n" + all[3];
2 Comments
IPAddress. Its not clear the reason you are converting the contents of AddressList to a string.int i=0;
String[] mylist;
foreach(ipaddress ip in list)
{
mylist[i]=ip.ToString();
i++
}