当我将一个对象添加到ObservableCollection中并查找它时,我遇到了奇怪的行为。刚添加完后可以找到,但是用相同的代码再次查找时却找不到了?
public class TestClass {
public TestClass(string s) {
Str = s;
}
public string Str {
get;
set;
}
}
private ObservableCollection<TestClass> testCollection = new ObservableCollection<TestClass>();
private List<string> newValueList = new List<string> { "one", "two", "three" };
private void Test() {
var tmpList = newValueList.Select(p => new TestClass(p));
foreach (var v in tmpList) {
testCollection.Add(v);
if (testCollection.Contains(v))
Console.WriteLine("YES");
else
Console.WriteLine("NO");
}
foreach (var v in tmpList) {
if (testCollection.Contains(v))
Console.WriteLine("IN");
else
Console.WriteLine("OUT");
}
}
运行此代码将得到输出:YES YES YES OUT OUT OUT
当使用.ToList()
对tmpList
进行操作,你将得到预期的结果。