foreach (Dictionary<string, object> dictionary in listOfDictionaries)
{
if( object.Equals(dictionary, listOfDictionaries.Last() )
{
//Do something on last iteration of foreach loop.
}
}我很快就意识到我想要一个引用等于,但它仍然提出了这个代码如何不能被击中的问题。object.Equals不是隐式知道如何比较两个字典,从而返回不相等吗?
发布于 2011-06-10 04:34:46
在这种情况下,有几种方法不能命中if语句体。
listOfDictionaries是一个空集合,因此tested.listOfDictionaries语句永远不会是if语句,它可能是一个生成的序列,它会在每次迭代时返回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
}
}
}发布于 2011-06-10 04:45:38
此测试通过。
什么事情没有像你预期的那样发生?
[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;
}
}https://stackoverflow.com/questions/6298869
复制相似问题