Simplify Your Code with LINQ

Posted by dwahlin on ASP.net Weblogs See other posts from ASP.net Weblogs or by dwahlin
Published on Thu, 01 Apr 2010 21:05:00 GMT Indexed on 2010/04/01 21:13 UTC
Read the original article Hit count: 310

Filed under:
|

I’m a big fan of LINQ and use it wherever I can to minimize code and make applications easier to maintain overall. I was going through a code file today refactoring it based on suggestions provided by Resharper and came across the following method:

private List<string> FilterTokens(List<string> tokens)
{
    var cleanedTokens = new List<string>();
    for (int i = 0; i < tokens.Count; i++)
    {
        string token = tokens[i];
        if (token != null)
        {
            cleanedTokens.Add(token);
        }
    }
    return cleanedTokens;
}

 

In looking through the code I didn’t see anything wrong but Resharper was suggesting that I convert it to a LINQ expression:

image

In thinking about it more the suggestion made complete sense because I simply wanted to add all non-null token values into a List<string> anyway. After following through with the Resharper suggestion the code changed to the following. Much, much cleaner and yet another example of why LINQ (and Resharper) rules:

private List<string> FilterTokens(IEnumerable<string> tokens)
{
    return tokens.Where(token => token != null).ToList();
}

© ASP.net Weblogs or respective owner

Related posts about c#

Related posts about LINQ