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

Dew Drop – December 16, 2011 (#1,221)

Top Links

 

.NET / Visual Studio

 

Web Development

 

Design / Methodology / Testing

 

Silverlight / WPF / Windows Phone

 

Podcasts / Screencasts / Videos

 

Community / Events

 

Database

 

PowerShell

 

Miscellaneous

 

More Link Collections

 

The Geek Shelf

Microsoft Windows Azure Development Cookbook by Neil Mackenzie

 

Mastodon
github.com/alvinashcraft