foreach (Item i in Items)
{
do something with i;
do another thing with i (but not if last item in collection);
}
foreach (Item i in Items)
{
do something with i;
do another thing with i (but not if last item in collection);
}
最好使用for循环:
int itemCount = Items.Count;
for (int i = 0; i < itemCount; i++)
{
var item = Items[i];
// do something with item
if (i != itemCount - 1)
{
// do another thing with item
}
}
IEnumerable<T>
本质上是有序的但没有索引。 - Jon Skeet我在这里使用MiscUtil中的帮助类来实现此功能。下面是示例代码(来自第一个链接):
foreach (SmartEnumerable<string>.Entry entry in
new SmartEnumerable<string>(list))
{
Console.WriteLine ("{0,-7} {1} ({2}) {3}",
entry.IsLast ? "Last ->" : "",
entry.Value,
entry.Index,
entry.IsFirst ? "<- First" : "");
}
如果您使用的是.NET 3.5和C# 3,则可以使用扩展方法和隐式类型,这样会更简单:
foreach (var entry in list.AsSmartEnumerable())
{
Console.WriteLine ("{0,-7} {1} ({2}) {3}",
entry.IsLast ? "Last ->" : "",
entry.Value,
entry.Index,
entry.IsFirst ? "<- First" : "");
}
与使用 for
循环相比,这种方法的好处在于它适用于 IEnumerable<T>
而不是 IList<T>
,因此可以与 LINQ 等一起使用而无需缓冲所有内容。(请注意,它在内部维护单个条目的缓冲区。)
foreach (Item i in Items.Take(Items.Count - 1))
{
do something with i;
do another thing with i (but not if last item in collection);
}
使用for循环代替foreach怎么样?
for (int i = 0; i < Items.Count; i++) {
//do something with i;
if (i == Items.Count - 1) {
//do another thing with Items[Items.count - 1];
}
}
如果你使用C#-3.0,你可以使用LINQ:
foreach (Item i in items.Take(Items.Count - 1))
{
...
}
正如Jon Siegel所指出的:
如果集合没有索引,那么最后一个项目的概念当然是没有意义的。
话虽如此,假设您想对 IEnumerable<T>
中除最后一个任意访问的枚举器之外的每个项目执行某些操作。 那就好办了:
IEnumerator<Item> e = Items.GetEnumerator();
e.MoveNext();
while (e.Current != null)
{
Item i = e.Current;
// do something with i;
if e.MoveNext()
{
// do another thing with i
}
}
看起来这就是你想要解决的问题。
List<string> list = getList();
string.Join(", ", list.ToArray());
我写这个可能会让我感觉很不舒服,但它可能会解决你的问题。
Item last = null;
foreach (Item i in Items)
{
last = i;
}
foreach (Item i in Items)
{
do something with i;
if (i!=last){
do another thing with i (but not if last item in collection);
}
}
您可以在按钮单击事件中按照这个逻辑进行操作。
namespace LastEnumItem
{
public partial class Form1 : Form
{
List<string> lst = new List<string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for(int i=0; i<=10 ; i++)
{
lst.Add("string " + i.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
string lastitem = lst[lst.Count-1];
foreach (string str in lst)
{
if (lastitem != str)
{
// do something
}
else
{
MessageBox.Show("Last Item :" + str);
}
}
}
}
}