Simplify Your Code with LINQ
- by dwahlin
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:
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();
}