【发布时间】:2020-03-30 23:10:25
【问题描述】:
假设我有 100 000 个 Person 类型的对象,其中有一个日期属性,其中包含他们的生日。
我将所有对象放在List<Person>(或数组)和字典中,其中我将日期作为键,每个值都是一个数组/列表,其中包含相同生日的人。
然后我这样做:
DateTime date = new DateTime(); // Just some date
var personsFromList = personList.Where(person => person.Birthday == date);
var personsFromDictionary = dictionary[date];
如果我运行 1000 次 Linq .Where 查找最终将比字典快得多。这是为什么?这对我来说似乎不合逻辑。结果是否在后台缓存(并再次使用)?
【问题讨论】:
-
.Where 还没有遍历列表,它只是准备了一个迭代器。添加 .ToList() 或 .First() 以获得更好的比较
-
Lambda 表达式只有在你执行例如 .ToList() 时才会被评估。参见例如stackoverflow.com/questions/6794555/…
-
什么意思?
int[] array = new int[] { 4, 6, 8, 4, 9 }; IEnumerable<int> fours = array.Where(x => x == 4); fours.Count(); // 2 elements当我这样做时,结果存储在变量“fours”中? -
fours.Count()是对IEnumerable的迭代,由.Where()调用准备
标签: linq dictionary