相关疑难解决方法(0)

LINQ性能计数vs Where和Count

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)

c# linq

29
推荐指数
2
解决办法
3755
查看次数

Linq Lambda与查询语法性能

我今天在我的项目中看到了一个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)

有人可以解释为什么会这样吗?

c# linq performance lambda linq-to-objects

13
推荐指数
2
解决办法
5647
查看次数

标签 统计

c# ×2

linq ×2

lambda ×1

linq-to-objects ×1

performance ×1