我遇到了 Linq 的一个奇怪行为:使用两个看起来相同的 linq 表达式,我得到了不同的结果!如果我循环一次得到相同的结果,但在上面什么也找不到。
这是代码:
Dictionary<String, String> mainDico = new Dictionary<String, String>();
mainDico.Add("key1", "value1");
mainDico.Add("key2", "value2");
List<Dictionary<String, String>> ls = new List<Dictionary<String, String>>();
Dictionary<String, String> fistDico = new Dictionary<String, String>();
fistDico.Add("key1", "value1");
fistDico.Add("key2", "value2");
Dictionary<String, String> secondDico = new Dictionary<String, String>();
secondDico.Add("key1", "other");
secondDico.Add("key2", "other");
ls.Add(fistDico);
ls.Add(secondDico);
IEnumerable<Dictionary<String, String>> failQuery = from p in ls
select p;
IEnumerable<Dictionary<String, String>> successfulQuery = from p in ls
select p;
String[] items = new String[] { "key1","key2" }; // with one element it works
foreach (var item in items)
{
String temp = mainDico[item];
failQuery = failQuery.Where(p => p[item] == temp);
successfulQuery = successfulQuery.Where(p => p[item] == mainDico[item]);
}
Console.WriteLine(successfulQuery.SingleOrDefault() != null);//True
Console.WriteLine(failQuery.SingleOrDefault() != null);//False