Reputation: 29311
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?
Upvotes: 1
Views: 140
Reputation: 754893
There are a couple of ways the body of the if
statement could not be hit in this scenario.
listOfDictionaries
is an empty collection hence the if
statement will never be tested.listOfDictionaries
could be a generated sequence which returns a new instance of Dictionary<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
using (var e = listOfDictionaries.GetEnumerator()) {
var hasMore = e.MoveNext();
while (hasMore) {
var dictionary = e.Current;
...
hasMore = e.MoveNext();
if (!hasMore) {
// Inside this if block dictionary is the last item in listOfDictionaries
}
}
}
Upvotes: 4
Reputation: 8108
This test passes.
What's not happening as you expect?
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
const int length = 10;
var j = 0;
List<Dictionary<string, object>> theList = new List<Dictionary<string, object>>();
for (int i = length - 1; i >= 0; i--)
{
var theDictionary = new Dictionary<string, object>();
theDictionary.Add("string-" + i + "-" + j++, new object());
theDictionary.Add("string-" + i + "-" + j++, new object());
theDictionary.Add("string-" + i + "-" + j++, new object());
theDictionary.Add("string-" + i + "-" + j++, new object());
theList.Add(theDictionary);
}
var theTested = new CodeToTest(theList);
var returnedValue = theTested.TestThis();
Assert.AreEqual(returnedValue,length);
}
}
class CodeToTest
{
private List<Dictionary<string, object>> listOfDictionaries;
public CodeToTest(List<Dictionary<string, object>> listOfDictionaries)
{
this.listOfDictionaries = listOfDictionaries;
}
public int TestThis()
{
var i = 0;
foreach (Dictionary<string, object> dictionary in listOfDictionaries)
{
i++;
if (object.Equals(dictionary, listOfDictionaries.Last()))
{
Console.WriteLine("Got here: " + i);
return i;
}
}
return 0;
}
}
Upvotes: 1