First, there is no ForEach
extension method for a Dictionary
or even an IEnumerable
. So you will have to fix that problem first.
Second, the Last
extension method will be painfully slow since it has to enumerate the entire collection.
Third, I am not sure it makes a whole lot of sense to do something special on the last item from a collection with an unpredictable order, but that is mostly tangential to your specific question.
Here is how I would approach the problem. Create two new extensions methods that operate on IEnumerable<T>
instances. ForEach
will be the equivalent of the List<T>.ForEach
method and WithIndex
will return another enumerator that contains the sequential index and an IsLast
flag. This is a variation of another one of my answers to a similiar problem.
dictionary.WithIndex().ForEach(
(item) =>
{
var kvp = item.Value; // This extracts the KeyValuePair
if (item.IsLast)
{
Console.WriteLine("Key=" + kvp.Key.ToString() + "; Value=" + kvp.Value.ToString());
}
});
Here are the new extension methods.
public static class ForEachHelperExtensions
{
public sealed class Item<T>
{
public int Index { get; set; }
public T Value { get; set; }
public bool IsLast { get; set; }
}
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
foreach (T item in enumerable)
{
action(item);
}
}
public static IEnumerable<Item<T>> WithIndex<T>(this IEnumerable<T> enumerable)
{
Item<T> item = null;
foreach (T value in enumerable)
{
Item<T> next = new Item<T>();
next.Index = 0;
next.Value = value;
next.IsLast = false;
if (item != null)
{
next.Index = item.Index + 1;
yield return item;
}
item = next;
}
if (item != null)
{
item.IsLast = true;
yield return item;
}
}
}