【问题标题】:Split string and convert to nullable long拆分字符串并转换为可为空的 long
【发布时间】:2019-07-30 09:29:41
【问题描述】:

我有以下代码拆分字符串,然后将值转换为长:

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

我想要的是将值转换为可为空的 long。 有什么帮助吗?

【问题讨论】:

标签: c#


【解决方案1】:

如果您只需要将其输入为long?,则只需输入Select

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

如果您需要使用null 来表示无法解析的内容,那么

Select(e => long.TryParse(e, out long r) ? r : default(long?))

【讨论】:

    【解决方案2】:

    使用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

    【讨论】:

    • 我会删除long temp; 行并改用out var temp。但我仍然不相信 OP 甚至需要这样做。
    【解决方案3】:

    你可以用这个,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      相关资源
      最近更新 更多