C# + ReSharper = Awesome: Tip #3 – Convert Into LINQ Expression

This is the third in a series of quick how-to articles on Resharper.

Tip #3 – Convert Into LINQ Expression

Use: ForEach blocks that perform simple bits of logic can often times be rewritten as lambda expressions. This reduces the number of lines of code and usually makes the code more readable.

Before
         public IList<Album> FindAlbumsToGiveAway(IList<Album> albums)
         {
             var badAlbums = new List<Album>();

             foreach (Album album in albums)
             {
                 if (album.Genre == "Country")
                     badAlbums.Add(album);
             }

             return badAlbums;
         }
Press <Alt+Enter>

image

After
         public IList<Album> FindAlbumsToGiveAway(IList<Album> albums)
         {
             return albums.Where(album => album.Genre == "Country").ToList();
         }

Happy coding!

 

del.icio.us Tags: ,,,

1 comment so far

  1. [...] if I was in a functional mood (example stolen shamelessly from Alvin Ashcraft). [...]

Leave a comment

Please be polite and on topic. Your e-mail will never be published.

 

About Me

I am a Philadelphia-area .NET developer, Microsoft MVP, husband, dad, and geek. I am currently a software engineer at Eclipsys Corporation. I have over 15 years of software development experience in the Healthcare and Manufacturing industries.

More...

Recent Posts

Archives