LINQ: Using int.TryParse() within a LINQ where clause

I pretty new to LINQ, and I’m keen to get more experience using it, so whenever an opportunity arises I like to try writing LINQ queries.


I needed to write a method to extract a comma separated list of numbers from a config file, and return this as List. I was looking at ways to do this using LINQ, but hit a problem. I wanted my LINQ query to filter out any values in the CSV string that could not be parsed as an int, without causing an exception. Using int.TryParse() seemed like a possible solution, but I had problems because the TryParse() method has an out parameter to store the parsed result. I ended up with the code below, which seems to work, but looks very messy, because I think it is parsing the string twice.


public static List<int> AuthorisedGroups
{
get
      {
            string[] authorisedGroupsStr = ConfigurationManager.AppSettings["AuthorisedGroups"].Split(new char[] { ',' });

int authorisedGroupInt;               

var authorisedGroupsInt = from authorisedGroupStr in authorisedGroupsStr
                                          where int.TryParse(authorisedGroupStr, out authorisedGroupInt)
                                          select int.Parse(authorisedGroupStr);
 
return authorisedGroupsInt.ToList();
}
}

I found in a blog.
Anybody have any suggestions of how to improve this code?


Comments

Popular posts from this blog

ASP.Net MVC: Configuring asp.net session state in SQL Server.

IIS: Publish Project to remote IIS with Web Deploy.