0

I have the following code which splits a string and then convert the values to long:

string.IsNullOrEmpty(baIds) ? null : baIds.Split(',').Select(e => long.Parse(e)).ToList(),

What I want is to convert the values to nullable long instead. Any help pls?

refresh
  • 1,319
  • 2
  • 20
  • 71

3 Answers3

1

If you just need it to be typed as long? then just cast in the Select

Select(e => (long?)long.Parse(e))

If you need to use null to indicate something that couldn't be parsed as long then

Select(e => long.TryParse(e, out long r) ? r : default(long?))
Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
0

Use TryParse

List<long?> result = null;
if (!string.IsNullOrEmpty(baIds))
{
    long temp;
    result = baIds.Split(',').Select(e => long.TryParse(e, out temp) ? temp : (long?)null).ToList();
}

https://dotnetfiddle.net/uHk99J

fubo
  • 44,811
  • 17
  • 103
  • 137
  • I would remove the `long temp;` line and use `out var temp` instead. But I'm still not convinced OP even needs to do this. – DavidG Mar 08 '19 at 10:57
0

You can use this,

string.IsNullOrEmpty(baIds) ? null : baIds.Split(',').Select(e => (long?)long.Parse(e)).ToList(),
Murat Acarsoy
  • 294
  • 3
  • 10