Performance concern when using LINQ "everywhere"?

Posted by stiank81 on Stack Overflow See other posts from Stack Overflow or by stiank81
Published on 2010-04-20T11:24:21Z Indexed on 2010/04/20 11:33 UTC
Read the original article Hit count: 277

Filed under:
|
|
|
|

After upgrading to ReSharper5 it gives me even more useful tips on code improvements. One I see everywhere now is a tip to replace foreach-statements with LINQ queries. Take this example:

private Ninja FindNinjaById(int ninjaId)
{
    foreach (var ninja in Ninjas)
    {
        if (ninja.Id == ninjaId)
            return ninja;
    }
    return null;
}

This is suggested replaced with the following using LINQ:

private Ninja FindNinjaById(int ninjaId)
{
    return Ninjas.FirstOrDefault(ninja => ninja.Id == ninjaId);
}

This looks all fine, and I'm sure it's no problem regarding performance to replace this one foreach. But is it something I should do in general? Or might I run into performance problems with all these LINQ queries everywhere?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#