我是C#的新手,所以如果这是一个简单的问题,我很抱歉
--
我有一个股票对象列表,我使用一个for循环向后遍历这个列表。stock对象的每个属性都设置为一个textbox以显示该值,并且有一个按钮允许用户循环每个对象,从而更改文本框的值。
我需要知道我是否到达列表的开头,这样我就可以禁用允许用户返回列表的按钮。
Note -计数>1,因为我必须跳过列表中的第一项。
这是我的代码:
if (stockList.Count > 1)
{
for (int i = stockList.Count - 1; i >= 0; i--)
{
txtName.Text = stockList[i].Name;
numLastPrice.Value = stockList[i].LastPrice;
numOpeningPrice.Value = stockList[i].OpeningPrice;
numLowPrice.Value = stockList[i].LowPrice;
numHighPrice.Value = stockList[i].HighPrice;
if (i == ???)
{
txtName.Text = stockList[i].Name;
numLastPrice.Value = stockList[i].LastPrice;
numOpeningPrice.Value = stockList[i].OpeningPrice;
numLowPrice.Value = stockList[i].LowPrice;
numHighPrice.Value = stockList[i].HighPrice;
btnBack.Enabled = false;
}
}发布于 2019-10-18 22:10:50
如果该列表中有10项,则从9返回到0(默认情况下索引为0)
在您的示例中,0表示列表中的第一项,所以只需检查索引是0
if (i == 0)(阅读评论后编辑)
在for循环中,您将i声明为一个值为.Count - 1的int
for (int i = stockList.Count - 1; i >= 0; i--)因此,在您的循环中,i只是一个变量,但是由于您声明它的方式,它也将是您在循环中迭代时列表的索引值。
希望这能有所帮助。
发布于 2019-10-19 03:30:53
我希望下面的片段帮助您了解i与列表之间的关系:
var myList = new List<string>() { "A", "B", "C", "D", "E" };
for (int i = myList.Count() - 1; i >= 0; i--)
{
Console.WriteLine($"i:{i}, myList[{i}]={myList[i]}");
if (i == 3)
{
//I can access the elements at an index different than `i`
Console.WriteLine($"i:{i}, Seaky peek at the 5th element (index 4): {myList[4]}");
}
}
// This would cause a compilation error because `i` is being used outside of `for`
//i = 100; // Error: The name 'i' does not exist in the current context
Console.WriteLine($"First item is myList[0] and is '{myList[0]}'");
Console.WriteLine($"Last item is myList[myLIst.Count()-1] ans is '{myList[myList.Count() - 1]}'");
// Let's go through the list again
for (int someNameForIndex = myList.Count() - 1; someNameForIndex >= 0; someNameForIndex--)
{
Console.WriteLine($"i:{someNameForIndex}, myList[{someNameForIndex}]={myList[someNameForIndex]}");
}这将生成以下输出
i:4, myList[4]=E
i:3, myList[3]=D
i:3, Seaky peek at the 5th element (index 4): E
i:2, myList[2]=C
i:1, myList[1]=B
i:0, myList[0]=A
First item is myList[0] and is 'A'
Last item is myList[myLIst.Count()-1] ans is 'E'
i:4, myList[4]=E
i:3, myList[3]=D
i:2, myList[2]=C
i:1, myList[1]=B
i:0, myList[0]=Ahttps://stackoverflow.com/questions/58458723
复制相似问题