stanleyR
stanleyR

Reputation: 33

Parse a string containing integers into a List<int>

I want to let the user enter integers in the following ways:

How can I parse a string that may be in any of the forms above an end up with a List of int?

So for example: 1-5,6,7-8 should give a list containing the ints 1,2,3,4,5,6,7,8

I'm pretty new to C# so some example code would be greatly appreciated. Thanks.

Upvotes: 2

Views: 1903

Answers (3)

Enigmativity
Enigmativity

Reputation: 117124

This works:

var query =
    from x in text.Split(',')
    let y = x.Split('-')
    let b = int.Parse(y[0].Trim())
    let e = int.Parse(y[y.Length - 1].Trim())
    from n in Enumerable.Range(b, e - b + 1)
    select n;

var result = query.ToList();

I would suggest adding some error handling, but if your input is in the correct format this works.


** EDIT**: The .NET 2.0 version.

var result = new List<int>();
foreach (var x in text.Split(','))
{
    var y = x.Split('-');
    var b = int.Parse(y[0].Trim());
    var e = int.Parse(y[y.Length - 1].Trim());
    for (var n = b; n <= e; n++)
    {
        result.Add(n);
    }
}

Much the same... :-)

Upvotes: 2

Gian Paolo
Gian Paolo

Reputation: 514

Tokenise the string based on the ',' then parse that list of individual numbers or ranges.

From memory there is a Split(..) method on List that you can use to get the tokens. Then just test fot the presence of a '-' (if its the first character then its negative, not a range obviously).

Upvotes: 0

Davide Piras
Davide Piras

Reputation: 44605

String.split splitting by comma , will give you all you need then if a group contains - split for it again and you have the two range values

Upvotes: 2

Related Questions