如何分配foreach迭代变量? [英] How do I assign a foreach iteration variable?
本文介绍了如何分配foreach迭代变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我有
Hello,
I have a
foreach
循环运行,我想为变量赋值,但我无法。它显示了一个错误:
loop running and I want to assign values to the variable but I am unable to. It shows me an error:
cannot assign because it is a foreach iteration variable
Visual Basic中的相同代码工作正常:
The same code in Visual Basic works fine:
For Each spline As String In Regex.Split(replicFile, vbNewLine)
Label9.Text = spline
Me.Refresh()
Do While spline.EndsWith(Chr(10)) Or spline.EndsWith(Chr(13))
spline = spline.Substring(0, spline.Length - 1)
Loop
Do While spline.StartsWith(Chr(10)) Or spline.StartsWith(Chr(13))
spline = spline.Substring(1, spline.Length - 1)
Loop
请帮忙。
问候
Aman Chaurasia
我的尝试:
Please help.
Regards
Aman Chaurasia
What I have tried:
foreach (string spline in Regex.Split(replicFile, Environment.NewLine))
{
Label9.Text = spline;
this.Refresh();
while (spline.EndsWith(('\n').ToString()) || spline.EndsWith(('\r').ToString()))
{
spline = spline.Substring(0, spline.Length - 1);
}
while (spline.StartsWith(('\n').ToString()) || spline.StartsWith(('\r').ToString()))
{
spline = spline.Substring(1, spline.Length - 1);
}
推荐答案
使用第二个变量:
Use a second variable:
foreach (string s in Regex.Split(replicFile, Environment.NewLine))
{
string spline = s;
Label9.Text = spline;
this.Refresh();
while (spline.EndsWith(('\n').ToString()) || spline.EndsWith(('\r').ToString()))
{
spline = spline.Substring(0, spline.Length - 1);
}
while (spline.StartsWith(('\n').ToString()) || spline.StartsWith(('\r').ToString()))
{
spline = spline.Substring(1, spline.Length - 1);
}
注意:您可以在循环时替换这两个只需一次调用 String.Trim [ ^ ]:
NB: You can replace both of those while
loops with a single call to String.Trim[^]:
foreach (string s in Regex.Split(replicFile, Environment.NewLine))
{
string spline = s;
Label9.Text = spline;
this.Refresh();
spline = spline.Trim(new[] { '\r', '\n' });
你必须使用等价的
for (int i=0; i< ;++) {}
或
while
循环,如果你想在循环时操纵集合。
Foreach不支持您的用例。
loop if you want to manipulate the collection while you loop over it.
Foreach does not support your use case.
这篇关于如何分配foreach迭代变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文