Linq iqueryable什么是更快:直接访问表还是通过对象层次结构?

时间:2018-05-18 08:57:40

标签: c# linq entity hierarchy

假设我有2个相关的表格: 候选人 - 包含通知的列表 所以问题是:

Candidates.SelectMany(c=>c.Notifications.Where(...).ToList())

或类似

var candIds = ...//int array of candidates that i need
Notifications.Where(n=>candId.Contains(n.CandidateId) && ...).ToList()

哪里表现更好? 这些表达方式是否相同?

1 个答案:

答案 0 :(得分:0)

如果没有您的数据集和上下文,我们无法告诉您哪种情况对您的方案更快。

我建议你做自己的测试场景:

var candIds = ...//int array of candidates that i need
var watch = new Stopwatch(); 
watch.Start();
Candidates.SelectMany(c=>c.Notifications.Where(...).ToList())
watch.Stop();
Console.WriteLine("Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds);
watch.Restart();
Notifications.Where(n=>candId.Contains(n.CandidateId) && ...).ToList();
watch.Stop();
Console.WriteLine("Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds);