public class Group
{
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
测试:
List<Group> _groups = new List<Group>();
for (int i = 0; i < 10000; i++)
{
var group = new Group();
group.Name = i + "asdasdasd";
_groups.Add(group);
}
Stopwatch _stopwatch2 = new Stopwatch();
_stopwatch2.Start();
foreach (var group in _groups)
{
var count = _groups.Count(x => x.Name == group.Name);
}
_stopwatch2.Stop();
Console.WriteLine(_stopwatch2.ElapsedMilliseconds);
Stopwatch _stopwatch = new Stopwatch();
_stopwatch.Start();
foreach (var group in _groups)
{
var count = _groups.Where(x => …Run Code Online (Sandbox Code Playgroud) 我今天在我的项目中看到了一个linq查询语法,它以List这种方式从特定条件的项目开始计算:
int temp = (from A in pTasks
where A.StatusID == (int)BusinessRule.TaskStatus.Pending
select A).ToList().Count();
Run Code Online (Sandbox Code Playgroud)
我想通过写它来重构它,就像使用Count()更易读,我认为它会表现得更好,所以我写道:
int UnassignedCount = pTasks.Count(x => x.StatusID == (int)BusinessRule.TaskStatus.Pending);
Run Code Online (Sandbox Code Playgroud)
但是,当我通过将StopWatchlambda表达式使用的时间进行检查时,总是比查询synax更多:
Stopwatch s = new Stopwatch();
s.Start();
int UnassignedCount = pTasks.Count(x => x.StatusID == (int)BusinessRule.TaskStatus.Pending);
s.Stop();
Stopwatch s2 = new Stopwatch();
s2.Start();
int temp = (from A in pTasks
where A.StatusID == (int)BusinessRule.TaskStatus.Pending
select A).ToList().Count();
s2.Stop();
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么会这样吗?