Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Performance 如何使用linq提高性能或简化.NET代码_Performance_Linq_.net 4.0 - Fatal编程技术网

Performance 如何使用linq提高性能或简化.NET代码

Performance 如何使用linq提高性能或简化.NET代码,performance,linq,.net-4.0,Performance,Linq,.net 4.0,除了数据库操作之外,如何使用LINQ简化或改进代码 示例 在字符串中搜索 string search=“在列表中搜索”; IEnumerable results=myList.Where(s=>s==search); 有了这么简单的东西,为什么不看看它是否存在 myList.Any(s => s == search) //which would return a boolean. 我经常在for循环中使用LINQ语句。作为一个简单的示例,而不是: for (int i = 0; i &l

除了数据库操作之外,如何使用LINQ简化或改进代码

示例 在字符串中搜索

string search=“在列表中搜索”;
IEnumerable results=myList.Where(s=>s==search);

有了这么简单的东西,为什么不看看它是否存在

myList.Any(s => s == search) //which would return a boolean.

我经常在for循环中使用LINQ语句。作为一个简单的示例,而不是:

for (int i = 0; i < array.Length; i++)
{
    if (array[i] > 10)
    {
        ...
    }
}
我经常发现自己需要获取列表中第一个出现的值:

var first = orders.FirstOrDefault(order => order.Items.Count > 1);

你刚才不是用这个例子回答了你自己的问题吗?@SLaks因为我对LINQ完全陌生,我想问一个问题,像你这样的优秀开发人员在编码时是如何利用LINQ的。我只是举了一个在Internet上随机找到的例子,请记住,使用LINQ很少能提高性能。相反地LINQ可能会简化代码的外观和读取(由人类读取),但根据我的经验,当您使用LINQ而不是传统循环时,代码的速度会大大降低。@Pedery感谢您的输入,我现在还将测试性能+1仅在查找项目存在时,不要使用count。找到第一行时,Any()将使调用短路。Count将遍历所有项。因此,Any()更有效。
foreach(var value in array.Where(item => item > 10))
{
    ...
}
var first = orders.FirstOrDefault(order => order.Items.Count > 1);