将字符串转换为可以为空的整数列表

时间:2021-04-10 16:09:23

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

我想在C#中将字符串解析为可以为空的int列表

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

我能够将它转换为int list bit而不是可空的

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 个解决方案

#1


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).

如果格式可能无效,我总是在LINQ查询中使用该扩展方法,它比使用局部变量和int.TryParse更好(E.Lippert给出了一个示例,请关注链接)。

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

除此之外,最好使用data.Split(new [] {','},StringSplitOptions.RemoveEmptyEntries)而不是首先省略空字符串。

#1


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).

如果格式可能无效,我总是在LINQ查询中使用该扩展方法,它比使用局部变量和int.TryParse更好(E.Lippert给出了一个示例,请关注链接)。

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

除此之外,最好使用data.Split(new [] {','},StringSplitOptions.RemoveEmptyEntries)而不是首先省略空字符串。