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: ,,,

One thought on “C# + ReSharper = Awesome: Tip #3 – Convert Into LINQ Expression

Comments are closed.