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 Answers1

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.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939