从循环 C# 添加到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12938937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:01:27  来源:igfitidea点击:

add to array from a loop C#

c#arraysstringloopsforeach

提问by Spreadzz

How can i add to an array wich is in a foreach loop.

我如何添加到一个位于 foreach 循环中的数组。

pseudo example

伪例子

String[] mylist;

foreach ( ipadress ip in list )
{
    i want to add to array ip.ToString();
}
then put my list to a textbox

采纳答案by Kundan Singh Chouhan

If you are using linq try this instead :

如果您使用的是 linq 试试这个:

String[] mylist = list.Select(I => Convert.ToString(I.ip)).ToArray();

回答by Kai

Quick and short:

快速而简短:

 String[] myList;

 List<int> intList = new List<int> { 1, 2, 3, 4 };

 myList = intList.ConvertAll<String>(p => p.ToString()).ToArray<String>();

回答by tharindlaksh

int i=0;
String[] mylist;
foreach(ipaddress ip in list)
{
mylist[i]=ip.ToString();
i++
}

回答by MadHenchbot

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[],并假设您的 ipaddress 类已重载 .ToString() 以返回一些智能信息:

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.

尽管我不得不质疑您为什么要在数组和列表对象之间来回切换。

回答by Spreadzz

Figured it out...new to programming.., thanks to all. I used same code that tharindlaksh posted.

想通了……编程新手……谢谢大家。我使用了 tharindlaksh 发布的相同代码。

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