See If a dictionary item is the last in a dictionary

Given the code ..

var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ? 

  // do something if this is the last item
});

I basically want to see if the element I'm working with inside the ForEach iteration is the last element in the dictionary. I tried

bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;

but it didn’t work ...

+3
source share
7 answers

Dictionary.Lastreturns KeyValuePair, and you compare it only with a key. Instead, you will need to check:

dictionary[item.Key].Equals( dictionary.Last().Value )

IAbstract was also right that you would probably need to use OrderedDictionary.

+7
source

You want to use OrderedDictionary<TKey, TValue>. Check MSDN Link

When using the standard dictionary, elements are not guaranteed in any particular order.

+2
source

, value == dictionary.Values.Last();

+1

?

string requiredForSomething = dictionary.Last().Value;
+1

.

int itemsCount = yourDictionary.Count;
bool isLast = false;

foreach(var item in yourDictionary)
{
   itemsCount--;       
   isLast = itemsCount == 0; 

   if(isLast)
   {
     // this is the last item no matter the order of the dictionary        
   }
   else
  {
    //not the last item
  }

}
+1

, , :

    dictionary[item.Key].Equals(dictionary.Last().Value) 

. , . , .


, , , Key, , , :

    item.Key.Equals(dictionary.Last().Key)
+1

-, ForEach Dictionary IEnumerable. .

-, Last , .

-, , - , .

. , IEnumerable<T>. ForEach List<T>.ForEach, WithIndex , IsLast. .

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());
    }
  });

.

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;
        }
    }
}
0

All Articles