Robin Hames

Hints, tricks and tips relating to MS SQL Server and .NET
posts - 14 , comments - 45 , trackbacks - 0

Wednesday, August 12, 2009

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<int>. 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.


Anybody have any suggestions of how to improve this code?


public static List<int> AuthorisedGroups




            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();




Posted On Wednesday, August 12, 2009 10:37 AM | Comments (7) |

Powered by: