foreach (Dictionary<string, object> dictionary in listOfDictionaries)
{
if( object.Equals(dictionary, listOfDictionaries.Last() )
{
//Do something on last iteration of foreach loop.
}
}
我很快意识到我想要一个引用等于,但它仍然提出了如何无法触及此代码的问题。 object.Equals是否隐式知道如何比较两个Dictionaries,因此返回不相等?
答案 0 :(得分:4)
在这种情况下,if
语句的主体有两种方法无法被识别。
listOfDictionaries
是一个空集合,因此永远不会测试if
语句。listOfDictionaries
可以是生成的序列,每次迭代时返回Dictionary<string, object>
的新实例,因此元素在迭代之间没有参照相等。 你能在这里给我们更多的背景吗?也许显示listOfDictionaries
的类型?
这是一个替代解决方案,不需要像.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
}
}
}
答案 1 :(得分:1)
此测试通过。
你没想到会发生什么?
[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;
}
}