![](/img/trans.png)
[英]Foreach loop, determine which is the last iteration of the loop - DataRow
[英]Foreach loop, determine which is the last iteration of the loop
我有一個foreach
循環,當從List
選擇最后一項時需要執行一些邏輯,例如:
foreach (Item result in Model.Results)
{
//if current result is the last item in Model.Results
//then do something in the code
}
我可以知道哪個循環最后而不使用 for 循環和計數器嗎?
如果你只需要對最后一個元素做一些事情(而不是對最后一個元素做一些不同的事情,那么使用 LINQ 在這里會有所幫助:
Item last = Model.Results.Last();
// do something with last
如果你需要對最后一個元素做一些不同的事情,那么你需要這樣的東西:
Item last = Model.Results.Last();
foreach (Item result in Model.Results)
{
// do something with each item
if (result.Equals(last))
{
// do something different with the last item
}
else
{
// do something different with every item but the last
}
}
盡管您可能需要編寫一個自定義比較器來確保您可以判斷該項目與Last()
返回的項目相同。
這種方法應該謹慎使用,因為Last
可能必須遍歷集合。 雖然這對於小型集合來說可能不是問題,但如果它變大,則可能會對性能產生影響。 如果列表包含重復項,它也會失敗。 在這種情況下,這樣的事情可能更合適:
int totalCount = result.Count();
for (int count = 0; count < totalCount; count++)
{
Item result = Model.Results[count];
// do something with each item
if ((count + 1) == totalCount)
{
// do something different with the last item
}
else
{
// do something different with every item but the last
}
}
一個好的老式 for 循環怎么樣?
for (int i = 0; i < Model.Results.Count; i++) {
if (i == Model.Results.Count - 1) {
// this is the last item
}
}
或者使用 Linq 和 foreach:
foreach (Item result in Model.Results)
{
if (Model.Results.IndexOf(result) == Model.Results.Count - 1) {
// this is the last item
}
}
正如 Chris 所示,Linq 會起作用; 只需使用 Last() 獲取對可枚舉中最后一個的引用,只要您不使用該引用,然后執行正常代碼,但如果您使用該引用,則執行額外的操作。 它的缺點是它總是 O(N) 復雜度。
您可以改為使用 Count()(如果 IEnumerable 也是 ICollection,則為 O(1);對於大多數常見的內置 IEnumerables 來說都是如此),並將您的 foreach 與計數器混合:
var i=0;
var count = Model.Results.Count();
foreach (Item result in Model.Results)
{
if (++i == count) //this is the last item
}
在某些類型上使用Last()
將遍歷整個集合!
這意味着如果你創建一個foreach
並調用Last()
,你就會循環兩次! 我相信你想避免在大集合中。
那么解決方案是使用do while
循環:
using var enumerator = collection.GetEnumerator();
var last = !enumerator.MoveNext();
T current;
while (!last)
{
current = enumerator.Current;
//process item
last = !enumerator.MoveNext();
if(last)
{
//additional processing for last item
}
}
因此,除非集合類型是IList<T>
類型,否則Last()
函數將遍歷所有集合元素。
如果您的集合提供隨機訪問(例如實現IList<T>
),您還可以按如下方式檢查您的項目。
if(collection is IList<T> list)
return collection[^1]; //replace with collection.Count -1 in pre-C#8 apps
var last = objList.LastOrDefault();
foreach (var item in objList)
{
if (item.Equals(last))
{
}
}
正如 Shimmy 所指出的,使用 Last() 可能是一個性能問題,例如,如果您的集合是 LINQ 表達式的實時結果。 為了防止多次迭代,您可以使用“ForEach”擴展方法,如下所示:
var elements = new[] { "A", "B", "C" };
elements.ForEach((element, info) => {
if (!info.IsLast) {
Console.WriteLine(element);
} else {
Console.WriteLine("Last one: " + element);
}
});
擴展方法看起來像這樣(作為額外的好處,它還會告訴您索引以及您是否正在查看第一個元素):
public static class EnumerableExtensions {
public delegate void ElementAction<in T>(T element, ElementInfo info);
public static void ForEach<T>(this IEnumerable<T> elements, ElementAction<T> action) {
using (IEnumerator<T> enumerator = elements.GetEnumerator())
{
bool isFirst = true;
bool hasNext = enumerator.MoveNext();
int index = 0;
while (hasNext)
{
T current = enumerator.Current;
hasNext = enumerator.MoveNext();
action(current, new ElementInfo(index, isFirst, !hasNext));
isFirst = false;
index++;
}
}
}
public struct ElementInfo {
public ElementInfo(int index, bool isFirst, bool isLast)
: this() {
Index = index;
IsFirst = isFirst;
IsLast = isLast;
}
public int Index { get; private set; }
public bool IsFirst { get; private set; }
public bool IsLast { get; private set; }
}
}
進一步改進Daniel Wolf 答案,您可以疊加另一個IEnumerable
以避免多次迭代和 lambda,例如:
var elements = new[] { "A", "B", "C" };
foreach (var e in elements.Detailed())
{
if (!e.IsLast) {
Console.WriteLine(e.Value);
} else {
Console.WriteLine("Last one: " + e.Value);
}
}
擴展方法實現:
public static class EnumerableExtensions {
public static IEnumerable<IterationElement<T>> Detailed<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
using (var enumerator = source.GetEnumerator())
{
bool isFirst = true;
bool hasNext = enumerator.MoveNext();
int index = 0;
while (hasNext)
{
T current = enumerator.Current;
hasNext = enumerator.MoveNext();
yield return new IterationElement<T>(index, current, isFirst, !hasNext);
isFirst = false;
index++;
}
}
}
public struct IterationElement<T>
{
public int Index { get; }
public bool IsFirst { get; }
public bool IsLast { get; }
public T Value { get; }
public IterationElement(int index, T value, bool isFirst, bool isLast)
{
Index = index;
IsFirst = isFirst;
IsLast = isLast;
Value = value;
}
}
}
迭代器實現沒有提供。 您的集合可能是可通過 O(1) 中的索引訪問的IList
。 在這種情況下,您可以使用普通的for
循環:
for(int i = 0; i < Model.Results.Count; i++)
{
if(i == Model.Results.Count - 1) doMagic();
}
如果您知道計數,但無法通過索引訪問(因此, result 是ICollection
),您可以通過增加foreach
主體中的i
並將其與長度進行比較來計算自己。
所有這些都不是完美的優雅。 克里斯的解決方案可能是迄今為止我見過的最好的解決方案。
更簡單的方法呢?
Item last = null;
foreach (Item result in Model.Results)
{
// do something with each item
last = result;
}
//Here Item 'last' contains the last object that came in the last of foreach loop.
DoSomethingOnLastElement(last);
最好的方法可能只是在循環后執行該步驟:例如
foreach(Item result in Model.Results)
{
//loop logic
}
//Post execution logic
或者如果你需要對最后的結果做些什么
foreach(Item result in Model.Results)
{
//loop logic
}
Item lastItem = Model.Results[Model.Results.Count - 1];
//Execute logic on lastItem here
接受的答案不適用於集合中的重復項。 如果您在foreach
上設置,則可以添加自己的索引變量。
int last = Model.Results.Count - 1;
int index = 0;
foreach (Item result in Model.Results)
{
//Do Things
if (index == last)
//Do Things with the last result
index++;
}
使用 Linq 和 foreach:
foreach (Item result in Model.Results)
{
if (Model.Results.IndexOf(result) == Model.Results.Count - 1) {
// this is the last item
}
}
“.Last()”對我不起作用,所以我不得不做這樣的事情:
Dictionary<string, string> iterativeDictionary = someOtherDictionary;
var index = 0;
iterativeDictionary.ForEach(kvp =>
index++ == iterativeDictionary.Count ?
/*it's the last item */ :
/*it's not the last item */
);
對 Jon Skeet 的優秀代碼進行一些小的調整,您甚至可以通過允許訪問上一個和下一個項目來使其更智能。 當然,這意味着您必須提前閱讀實現中的 1 項。 出於性能原因,上一項和下一項僅保留當前迭代項。 它是這樣的:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Based on source: http://jonskeet.uk/csharp/miscutil/
namespace Generic.Utilities
{
/// <summary>
/// Static class to make creation easier. If possible though, use the extension
/// method in SmartEnumerableExt.
/// </summary>
public static class SmartEnumerable
{
/// <summary>
/// Extension method to make life easier.
/// </summary>
/// <typeparam name="T">Type of enumerable</typeparam>
/// <param name="source">Source enumerable</param>
/// <returns>A new SmartEnumerable of the appropriate type</returns>
public static SmartEnumerable<T> Create<T>(IEnumerable<T> source)
{
return new SmartEnumerable<T>(source);
}
}
/// <summary>
/// Type chaining an IEnumerable<T> to allow the iterating code
/// to detect the first and last entries simply.
/// </summary>
/// <typeparam name="T">Type to iterate over</typeparam>
public class SmartEnumerable<T> : IEnumerable<SmartEnumerable<T>.Entry>
{
/// <summary>
/// Enumerable we proxy to
/// </summary>
readonly IEnumerable<T> enumerable;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="enumerable">Collection to enumerate. Must not be null.</param>
public SmartEnumerable(IEnumerable<T> enumerable)
{
if (enumerable == null)
{
throw new ArgumentNullException("enumerable");
}
this.enumerable = enumerable;
}
/// <summary>
/// Returns an enumeration of Entry objects, each of which knows
/// whether it is the first/last of the enumeration, as well as the
/// current value and next/previous values.
/// </summary>
public IEnumerator<Entry> GetEnumerator()
{
using (IEnumerator<T> enumerator = enumerable.GetEnumerator())
{
if (!enumerator.MoveNext())
{
yield break;
}
bool isFirst = true;
bool isLast = false;
int index = 0;
Entry previous = null;
T current = enumerator.Current;
isLast = !enumerator.MoveNext();
var entry = new Entry(isFirst, isLast, current, index++, previous);
isFirst = false;
previous = entry;
while (!isLast)
{
T next = enumerator.Current;
isLast = !enumerator.MoveNext();
var entry2 = new Entry(isFirst, isLast, next, index++, entry);
entry.SetNext(entry2);
yield return entry;
previous.UnsetLinks();
previous = entry;
entry = entry2;
}
yield return entry;
previous.UnsetLinks();
}
}
/// <summary>
/// Non-generic form of GetEnumerator.
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Represents each entry returned within a collection,
/// containing the value and whether it is the first and/or
/// the last entry in the collection's. enumeration
/// </summary>
public class Entry
{
#region Fields
private readonly bool isFirst;
private readonly bool isLast;
private readonly T value;
private readonly int index;
private Entry previous;
private Entry next = null;
#endregion
#region Properties
/// <summary>
/// The value of the entry.
/// </summary>
public T Value { get { return value; } }
/// <summary>
/// Whether or not this entry is first in the collection's enumeration.
/// </summary>
public bool IsFirst { get { return isFirst; } }
/// <summary>
/// Whether or not this entry is last in the collection's enumeration.
/// </summary>
public bool IsLast { get { return isLast; } }
/// <summary>
/// The 0-based index of this entry (i.e. how many entries have been returned before this one)
/// </summary>
public int Index { get { return index; } }
/// <summary>
/// Returns the previous entry.
/// Only available for the CURRENT entry!
/// </summary>
public Entry Previous { get { return previous; } }
/// <summary>
/// Returns the next entry for the current iterator.
/// Only available for the CURRENT entry!
/// </summary>
public Entry Next { get { return next; } }
#endregion
#region Constructors
internal Entry(bool isFirst, bool isLast, T value, int index, Entry previous)
{
this.isFirst = isFirst;
this.isLast = isLast;
this.value = value;
this.index = index;
this.previous = previous;
}
#endregion
#region Methods
/// <summary>
/// Fix the link to the next item of the IEnumerable
/// </summary>
/// <param name="entry"></param>
internal void SetNext(Entry entry)
{
next = entry;
}
/// <summary>
/// Allow previous and next Entry to be garbage collected by setting them to null
/// </summary>
internal void UnsetLinks()
{
previous = null;
next = null;
}
/// <summary>
/// Returns "(index)value"
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("({0}){1}", Index, Value);
}
#endregion
}
}
}
如何將foreach
轉換為對最后一個元素做出反應:
List<int> myList = new List<int>() {1, 2, 3, 4, 5};
Console.WriteLine("foreach version");
{
foreach (var current in myList)
{
Console.WriteLine(current);
}
}
Console.WriteLine("equivalent that reacts to last element");
{
var enumerator = myList.GetEnumerator();
if (enumerator.MoveNext() == true) // Corner case: empty list.
{
while (true)
{
int current = enumerator.Current;
// Handle current element here.
Console.WriteLine(current);
bool ifLastElement = (enumerator.MoveNext() == false);
if (ifLastElement)
{
// Cleanup after last element
Console.WriteLine("[last element]");
break;
}
}
}
enumerator.Dispose();
}
只需存儲先前的值並在循環內使用它。 然后最后“上一個”值將是最后一項,讓您以不同的方式處理它。 無需計數或特殊庫。
bool empty = true;
Item previousItem;
foreach (Item result in Model.Results)
{
if (!empty)
{
// We know this isn't the last item because it came from the previous iteration
handleRegularItem(previousItem);
}
previousItem = result;
empty = false;
}
if (!empty)
{
// We know this is the last item because the loop is finished
handleLastItem(previousItem);
}
您可以只使用 for 循環,而無需在for
主體內添加額外的if
:
for (int i = 0; i < Model.Results.Count - 1; i++) {
var item = Model.Results[i];
}
for
條件中的-1
負責跳過最后一項。
根據@Shimmy 的回復,我創建了一個擴展方法,這是每個人都想要的解決方案。 它簡單,易於使用,並且只循環一次集合。
internal static class EnumerableExtensions
{
public static void ForEachLast<T>(this IEnumerable<T> collection, Action<T>? actionExceptLast = null, Action<T>? actionOnLast = null)
{
using var enumerator = collection.GetEnumerator();
var isNotLast = enumerator.MoveNext();
while (isNotLast)
{
var current = enumerator.Current;
isNotLast = enumerator.MoveNext();
var action = isNotLast ? actionExceptLast : actionOnLast;
action?.Invoke(current);
}
}
}
這適用於任何IEnumerable<T>
。 用法如下所示:
var items = new[] {1, 2, 3, 4, 5};
items.ForEachLast(i => Console.WriteLine($"{i},"), i => Console.WriteLine(i));
輸出看起來像:
1,
2,
3,
4,
5
此外,您可以將其設為Select
樣式方法。 然后,在ForEach
重用該擴展。 該代碼如下所示:
internal static class EnumerableExtensions
{
public static void ForEachLast<T>(this IEnumerable<T> collection, Action<T>? actionExceptLast = null, Action<T>? actionOnLast = null) =>
// ReSharper disable once IteratorMethodResultIsIgnored
collection.SelectLast(i => { actionExceptLast?.Invoke(i); return true; }, i => { actionOnLast?.Invoke(i); return true; }).ToArray();
public static IEnumerable<TResult> SelectLast<T, TResult>(this IEnumerable<T> collection, Func<T, TResult>? selectorExceptLast = null, Func<T, TResult>? selectorOnLast = null)
{
using var enumerator = collection.GetEnumerator();
var isNotLast = enumerator.MoveNext();
while (isNotLast)
{
var current = enumerator.Current;
isNotLast = enumerator.MoveNext();
var selector = isNotLast ? selectorExceptLast : selectorOnLast;
//https://stackoverflow.com/a/32580613/294804
if (selector != null)
{
yield return selector.Invoke(current);
}
}
}
}
Jon Skeet SmartEnumerable<T>
創建了一個SmartEnumerable<T>
類型來解決這個確切的問題。 你可以在這里看到它的實現:
為了對除最后一個元素之外的每個元素做一些額外的事情,可以使用基於函數的方法。
delegate void DInner ();
....
Dinner inner=delegate
{
inner=delegate
{
// do something additional
}
}
foreach (DataGridViewRow dgr in product_list.Rows)
{
inner()
//do something
}
}
這種方法有明顯的缺點:對於更復雜的情況,代碼清晰度較低。 呼叫代表可能不是很有效。 故障排除可能並不容易。 好的一面 - 編碼很有趣!
話雖如此,如果您知道您的集合計數不是非常慢,我建議在瑣碎的情況下使用普通的 for 循環。
另一種我沒有看到發布的方法是使用隊列。 它類似於實現 SkipLast() 方法而無需進行不必要的迭代的方法。 這種方式還允許您對任意數量的最后一個項目執行此操作。
public static void ForEachAndKnowIfLast<T>(
this IEnumerable<T> source,
Action<T, bool> a,
int numLastItems = 1)
{
int bufferMax = numLastItems + 1;
var buffer = new Queue<T>(bufferMax);
foreach (T x in source)
{
buffer.Enqueue(x);
if (buffer.Count < bufferMax)
continue; //Until the buffer is full, just add to it.
a(buffer.Dequeue(), false);
}
foreach (T item in buffer)
a(item, true);
}
要調用它,您需要執行以下操作:
Model.Results.ForEachAndKnowIfLast(
(result, isLast) =>
{
//your logic goes here, using isLast to do things differently for last item(s).
});
List<int> ListInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int count = ListInt.Count;
int index = 1;
foreach (var item in ListInt)
{
if (index != count)
{
Console.WriteLine("do something at index number " + index);
}
else
{
Console.WriteLine("Foreach loop, this is the last iteration of the loop " + index);
}
index++;
}
//OR
int count = ListInt.Count;
int index = 1;
foreach (var item in ListInt)
{
if (index < count)
{
Console.WriteLine("do something at index number " + index);
}
else
{
Console.WriteLine("Foreach loop, this is the last iteration of the loop " + index);
}
index++;
}
您可以專門為此創建一個擴展方法:
public static class EnumerableExtensions {
public static bool IsLast<T>(this List<T> items, T item)
{
if (items.Count == 0)
return false;
T last = items[items.Count - 1];
return item.Equals(last);
}
}
你可以像這樣使用它:
foreach (Item result in Model.Results)
{
if(Model.Results.IsLast(result))
{
//do something in the code
}
}
我們可以檢查循環中的最后一項。
foreach (Item result in Model.Results)
{
if (result==Model.Results.Last())
{
// do something different with the last item
}
}
foreach (DataRow drow in ds.Tables[0].Rows)
{
cnt_sl1 = "<div class='col-md-6'><div class='Slider-img'>" +
"<div class='row'><img src='" + drow["images_path"].ToString() + "' alt='' />" +
"</div></div></div>";
cnt_sl2 = "<div class='col-md-6'><div class='Slider-details'>" +
"<p>" + drow["situation_details"].ToString() + "</p>" +
"</div></div>";
if (i == 0)
{
lblSituationName.Text = drow["situation"].ToString();
}
if (drow["images_position"].ToString() == "0")
{
content += "<div class='item'>" + cnt_sl1 + cnt_sl2 + "</div>";
cnt_sl1 = "";
cnt_sl2 = "";
}
else if (drow["images_position"].ToString() == "1")
{
content += "<div class='item'>" + cnt_sl2 + cnt_sl1 + "</div>";
cnt_sl1 = "";
cnt_sl2 = "";
}
i++;
}
你可以這樣做:
foreach (DataGridViewRow dgr in product_list.Rows)
{
if (dgr.Index == dgr.DataGridView.RowCount - 1)
{
//do something
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.