foreach (Dictionary<string, object> dictionary in listOfDictionaries)
{
if( object.Equals(dictionary, listOfDictionaries.Last() )
{
//Do something on last iteration of foreach loop.
}
}
I realized fairly soon on that I wanted a reference equals, but it still brought up the question of how this code could not be hit. Does object.Equals not implicitly know how to compare two Dictionaries, and thus returns not equal?
There are a couple of ways the body of the
ifstatement could not be hit in this scenario.listOfDictionariesis an empty collection hence theifstatement will never be tested.listOfDictionariescould be a generated sequence which returns a new instance ofDictionary<string, object>every time it’s iterated and hence the elements do not have referential equality between iterations.Could you give us a bit more context here? Perhaps show the type of
listOfDictionaries?Here’s an alternative solution that doesn’t require any extra allocations as would be incurred with
.ToList