0

I'm wanting to parse a string into a nullable int list in C#

I'm able to convert it to int list bit not a nullable one

string data = "1,2";
List<int> TagIds = data.Split(',').Select(int.Parse).ToList();

say when data will be empty i want to handle that part!

Thanks

1 Answer 1

4

You can use following extension method:

public static int? TryGetInt32(this string item)
{
    int i;
    bool success = int.TryParse(item, out i);
    return success ? (int?)i : (int?)null;
}

Then it's simple:

List<int?> TagIds = data.Split(',')
    .Select(s => s.TryGetInt32())
    .ToList();

I use that extension method always in LINQ queries if the format can be invalid, it's better than using a local variable and int.TryParse (E. Lippert gave an example, follow link).

Apart from that it may be better to use data.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries) instead which omits empty strings in the first place.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to do this without an extension method?
@IfeoluwaOsungade: You can call every extension method as a normal static method(ClassName.MethodName).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.