Return the declared out variable in int.TryParse with LINQ from a list of strings

958 views Asked by At

I have a string like this:

/Location/12345/

But I only need the number 12345.

The following function returns the number:

    private int GetNumberFromString(string location = "/Location/12345/")
    {
        var id = 0;
        var strings = location.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
        strings.FirstOrDefault(t => int.TryParse(t, out id));
        return id;
    }

I would like to do something like this:

    private int GetNumberFromString(string location = "/Location/12345/")
    {
        var strings = location.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
        return strings.FirstOrDefault(t => int.TryParse(t, out var id));
    }

But that returns string and not int.

So is it possible to declare the variable id inside of int.TryParse and return it immediately? Or is there a better solution for this?

2

There are 2 answers

1
GGO On BEST ANSWER

With a regex ?

return int.Parse(new Regex("\\d+").Match("/location/1234/").Groups[0].Value)
2
gilliduck On

Not the best solution I'm sure, but it works.

private int GetNumberFromStringLinq(string location = "/Location/12345/")
        {
            var strings = location.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            return Convert.ToInt32(strings.FirstOrDefault(t => int.TryParse(t, out var id)));
        }