[英]How do I escape a foreach loop during last iteration?
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
}
}
我在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];
}
}
您可以使用LINQ(如果您使用C#-3.0):
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);
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.