从其他if循环中的foreach循环中c#
问题描述:
我有一个foreach循环和里面,如果有其他循环,为每个循环我检查文本文件的行,首先我检查第一行是“ctf”如果不是从所有循环中退出,否则它是“ctf”,然后在foreach循环中取下一行并转到其他部分,但是我的其他部分检查第一行可以有人说什么是实际问题。从其他if循环中的foreach循环中c#
bool first = true;int i=0;
lines = streamReader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (first)
{
if (line != "CTF") { break; } // i think the problem is here.
first = false;
}
else
{
tabs = line.Split('\t');
ID = int.Parse(tabs[0]);
X = int.Parse(tabs[1]);
Y = int.Parse(tabs[2]);
H = int.Parse(tabs[3]);
W = int.Parse(tabs[4]);
Text = tabs[5];
ItemTypes types = (ItemTypes)int.Parse(tabs[6]);
Items.Add(new FormItem());
Items[i].Id = ID;
Items[i].X = X;
Items[i].Y = Y;
Items[i].Height = H;
Items[i].Width = W;
Items[i].Text = Text;
Items[i].Type = types;
i++;
}
答
交换的“如果”的身体顺序检查
if (first)
{
first = false;
if (line != "CTF") { break; }
}
你的问题是,布尔变量“第一”不被设置为false,如果第一行是不是“周大福”。
答
假设它可以是一个外壳问题考虑从以下变化...
if (line != "CTF") { break; }
到...
if (string.Compare(line, "CTF", true)== 0) { break; }
祝您好运!
答
写第一= FALSE其他
foreach (string line in lines)
{
if (first)
{
if (line != "CTF") { break; } // i think the problem is here.
}
else
{
tabs = line.Split('\t');
ID = int.Parse(tabs[0]);
X = int.Parse(tabs[1]);
Y = int.Parse(tabs[2]);
H = int.Parse(tabs[3]);
W = int.Parse(tabs[4]);
Text = tabs[5];
ItemTypes types = (ItemTypes)int.Parse(tabs[6]);
Items.Add(new FormItem());
Items[i].Id = ID;
Items[i].X = X;
Items[i].Y = Y;
Items[i].Height = H;
Items[i].Width = W;
Items[i].Text = Text;
Items[i].Type = types;
i++;
}
first = false;
}
后的问题已经回答了,但作为一般规则,如果你要跳出循环的,最好的做法是使用一个do while循环,而不是的foreach。 –