如何使用foreach循环获得字符串数组项值?



代码如下:

string[] wordsX ={"word1", "word2","word3"}

与foreach循环想要获取项值并传递给标签

foreach (string w in wordsX)
{
Label1.Text = w[1].ToString();
Label2.Text = w[2].ToString();
}

返回一个错误:Index超出了数组的边界。

您面临的问题是,您希望将标签的值设置为wordX元素的值

在您编写额外的if语句和开关之前。你可以用一些巧妙的方法。诀窍是,创建一个标签数组然后对它们进行压缩

像这样:

public static void Main()
{
// the words
string[] wordsX ={"word1", "word2","word3"};
// the labels as array
Label[] labels = {Label1, Label2};

// zip them together into a new anonymous class
// (use the shortest collection)
var combined = wordsX.Zip(labels, (w, l) => new { Word = w, Label = l});

// display them with foreach.
foreach (var item in combined)
{
// assign the label.Text to the word
item.Label.Text = item.Word;
}
}

击穿:

// first collection
var combined = wordsX                
// second collection
.Zip(labels,      
// function to return new instance (class with no name)
(w, l) => new { Word = w, Label = l}); 

您需要通过运行时字符串而不是编译时符号访问您的标签。您可以使用Controls.Find.

string[] wordsX ={"word1", "word2","word3"};
for (int i=0; i< wordsX.Length; i++)
{
var controlId = string.Format("Label{0}", i);
var control = this.Control.Find(controlId).OfType<Label>().FirstOrDefault();
if (control != null) control.Text = wordsX[i];
}

像所有问题一样,我们不知道是否只有3个值,或者说1 '到15个值(页面上的标签)

更糟糕的是为什么要使用循环并且必须输入标签名称-即使是在数组中?(违背了使用循环的全部目的!)。

那么,让我们假设一个列表,比如1到10个项目,因此:

Lable1
Lable2
... to 10, or 20, or 5 or 50!!!!

好了,我们不仅需要处理传递一个只有5个值的列表,我们还需要清空那些没有值的(或者这里有人想到????)

那么,你可以这样做:

List<string> Mylist = new List<string> { "one", "Two", "Three", "Four" };
for (int i = 1; i <= 10; i++)
{
Label MyLabel = Page.FindControl("Label" + i) as Label;
if (i <= Mylist.Count)
MyLabel.Text = Mylist[i-1];
else
MyLabel.Text = "";
}

上面假设我们有Label1到label10,但它可以为5或50或任何你有多少。

最新更新