这是 C# 中将分隔字符串转换为 int 数组的最佳方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/797750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:34:44  来源:igfitidea点击:

Is this the best way in C# to convert a delimited string to an int array?

c#string

提问by Soni Ali

Given the string below:

鉴于以下字符串:

string str = "1,2,3";

Will this be the best extension to convert it to an intarray?

这将是将其转换为int数组的最佳扩展吗?

static class StringExtensions
{
    public static int[] ToIntArray(this string s)
    {
        return ToIntArray(s, ',');
    }
    public static int[] ToIntArray(this string s, char separator)
    {
        string[] ar = s.Split(separator);
        List<int> ints = new List<int>();
        foreach (var item in ar)
        {
            int v;
            if (int.TryParse(item, out v))
                ints.Add(v);
        }
        return ints.ToArray();
    }
}

采纳答案by Marc Gravell

It really depends what you want to do with the non-integer strings. At the moment you silently drop them. Personally, I'd want it to error. This also lets you use the more terse:

这真的取决于你想用非整数字符串做什么。此刻你默默地放下它们。就个人而言,我希望它出错。这也让你可以使用更简洁的:

public static int[] ToIntArray(this string value, char separator)
{
    return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));
}

回答by Richard Ev

This approach is very terse, and will throw a (not very informative) FormatExceptionif the split string contains any values that can't be parsed as an int:

这种方法非常简洁,FormatException如果拆分字符串包含任何无法解析为 int 的值,则会抛出一个(信息量不大):

int[] ints = str.Split(',').Select(s => int.Parse(s)).ToArray();

If you just want to silently drop any non-int values you could try this:

如果你只是想默默地删除任何非 int 值,你可以试试这个:

private static int? AsNullableInt(string s)
{
    int? asNullableInt = null;

    int asInt;

    if (int.TryParse(s, out asInt))
    {
        asNullableInt = asInt;
    }

    return asNullableInt;
}

// Example usage...
int[] ints = str.Split(',')
    .Select(s => AsNullableInt(s))
    .Where(s => s.HasValue)
    .Select(s => s.Value)
    .ToArray();

回答by Otávio Décio

It looks OK, I would also throw an exception if one of the items could not be converted instead of silently failing.

看起来不错,如果其中一项无法转换而不是静默失败,我也会抛出异常。

回答by Winston Smith

This will blow up if one of your elements in the list does not parse as int, which is probably better than silently failing:

如果列表中的元素之一没有解析为 int,这将爆炸,这可能比静默失败要好:

public static int[] ToIntArray(this string value, char separator)
{
    return value.Split(separator).Select(i => int.Parse(i)).ToArray();
}