如何在字符串数组中获取值“”以被视为“0”

本文关键字:字符串 数组 获取 | 更新日期: 2023-09-27 18:36:11

我一直无法找到这个问题的解决方案,如果有人能看到一个,我将不胜感激。

我有一个字符串数组。通常字符串数组将包含多个字符串 ID(例如"1"、"2"、"3"),但有时它会包含一个空字符串(即值为 " 的字符串)。(这无法更改,因为它是系统设计不可或缺的一部分。

然后,字符串 Id 将转换为整数,并存储在列表中,但如果字符串 ID 为 ",则转换不起作用,因为无法将空字符串转换为整数,因为它没有等效的数字。

我正在尝试使用 Replace 方法,用"0"

替换空字符串,然后将其转换为 0,但 Replace 方法不会替换"的实例,因为我本质上是说,替换什么都没有的实例,这没有意义。

foreach (string stringId in stringArray)
{
    intList.Add(Convert.ToInt32(stringId.Replace("", "0")));
}

所以我的问题是,如何让字符串数组中的"实例被视为或转换为"0"?

如何在字符串数组中获取值“”以被视为“0”

使用上面的技术,你只需要包含一个条件检查:

foreach (string stringId in stringArray)
{
    intList.Add(Convert.ToInt32((stringId == "" ? "0" : stringId)));
}

您还可以将 ConvertAll 用于单行实现:

intList = Array.ConvertAll(stringArray, s => (s == "" ? 0 : int.Parse(s))).ToList();

将其分解为多个语句:

foreach (string stringId in stringArray)
{
    if (!string.IsNullOrWhiteSpace(stringId)) {
         intList.Add(Convert.ToInt32(stringId));
    }
    else {
      intList.Add(0);
    }
}

或使用int.TryParse .

foreach (string stringId in stringArray)
{
    int id;
    int.TryParse(stringId, out id);
    intList.Add(id);
}

您可以使用 LINQ:

 intList = stringArray.Select(str => String.IsNullOrEmpty(str) ? 0 : Int32.Parse(str))
                      .ToList();

或与同一代表Array.ConvertAll

intList = Array.ConvertAll(stringArray, str => String.IsNullOrEmpty(str) ? 0 : Int32.Parse(str))
               .ToList();