linq中关于Exists与Find性能比较

1 前几天发现同事写这样的代码

Person enPerson = new Person();
if (lstPerson.Exists(p => p.SName == "张三"))
{
enPerson = lstPerson.Find(p => p.SName == "张三").Age;
}
return enPerson;

我在想,lstPerson.Exists(p => p.SName == "张三") 这一步的目的,不就是为了:  lstPerson.Find(p => p.SName == "张三") 查询出来的实体不为NULL.

于是:我这样写了.

Person enPerson = new Person();
enPerson = lstPerson.Find(p => p.SName == "张三");
if (enPerson != null)
{
   enPerson.Age;
}

经过测试:

Stopwatch sp = new Stopwatch();
sp.Start();
------
sp.Stop();
int k = sp.Elapsed.Milliseconds;

我改过之后的代码 效率比改之前的高一倍.

posted @ 2015-12-20 18:48  No.net  阅读(1419)  评论(0编辑  收藏  举报