Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See if Dictionary Item is the last one in the 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 item I am working with inside of the ForEach iteration is the last item in the dictionary. I tried

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

but that did not work...

like image 899
Ciel Avatar asked Nov 30 '22 08:11

Ciel


1 Answers

Dictionary.Last returns a KeyValuePair, and you are comparing that to just the value of a key. You'd instead need to check:

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

Also IAbstract was correct that you'd probably need to use an OrderedDictionary.

like image 55
Chris Walsh Avatar answered Dec 02 '22 22:12

Chris Walsh