Robin Hames

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

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

{

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

}

}

 

Print | posted on Wednesday, August 12, 2009 10:37 AM | Filed Under [ LINQ C# ]

Feedback

Gravatar

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

Pretty easy actually... try using int.Parse(string), and wrapping it in a try/catch.

static void Main(string[] args)
{
string values = "12 , 55 , 3, 104 , 89 ";

var results = GetIntegers(values);

if (results != null)
foreach (var result in results)
Console.WriteLine(result);

Console.ReadKey();
}

static List<int> GetIntegers(string s)
{
try
{
return (from value in s.Split(',')
let integer = int.Parse(value.Trim())
select integer).ToList();
}
catch(Exception exception)
{
// display the error to the user
Console.WriteLine(exception.Message);
return null;
}
}


Notice I used a range variable called "integer". You could just as easily ditch it, and just select int.Parse(value.Trim()). Doesn't matter really, it's more of a stylistic thing. If the int.Parse fails, the catch is there to report the error and recover from the error.
8/12/2009 1:35 PM | John Nelson
Gravatar

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

With this method, won't the exception mean that any input string that contains non-int values will not be read at all. I wanted any non-int values to just be ignored, with the remaining int values still being returned. For example, if the input string array is {"12, 13, 14, sddedf, 20"}, I wanted the returned list to contain 12, 13, 14, 20.
8/12/2009 1:53 PM | Robin
Gravatar

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

One simple way.

string[] authorisedGroupsStr = { "12", "13", "14", "sddedf", "20", "dfsf3535", "12.34-", "56", "13.00" };

var authorisedGroupInt = 0;

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

8/12/2009 6:19 PM | rusty
Gravatar

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

The solution posted by rusty is exactly what I was after. I did try something very similar but was getting a compile error. I was declaring authorisedGroupInt as an int and I wasn't assigning a value to it. After playing around a bit more, it seems the fact that no value was initially assigned caused the compile error. I should have guessed this because the error was "Use of unassigned local variable".
8/12/2009 11:41 PM | Robin
Gravatar

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

For VB folks, the code is slightly different.

Dim intVal As Integer
Dim intVals As IEnumerable(Of Integer) =
(From value As String In strCountryIds
Where Integer.TryParse(value, intVal)
Select val = intVal)

Note that you cannot simply select intVal because you will get a message about obscuring the previously defined variable.

Thanks for posting this article.. Very helpful.
8/12/2010 6:57 PM | Richard Collette
Gravatar

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

i love post
1/7/2011 6:51 AM | Taobao auction
Gravatar

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

Someone asked a similiar question over on Stack overflow and Jon Skeet provided an alternative that doesn't have the same side effects as your solution: http://stackoverflow.com/questions/4961675/linq-select-parsed-int-if-string-was-parseable-to-int/4961697#4961697
9/2/2011 7:18 PM | Jonathan Schellack
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 
 

Powered by: