以下是实现代码:

List<string> strList = new List<string>();
bool hasOne = false;
bool hasTwo = false;
foreach (string str in strList)
{
    if (str == '1')
    {
        hasOne = true;
    }
    else if (str == '2')
    {
        hasTwo = true;
    }
}

if (hasOne && hasTwo)
{
    return 3;
}
 else if (hasOne)
{
    return 1;
}
 else if (hasTwo)
{
    return 2;
}
 else
{
    // 如果列表为空,或者既没有1也没有2,则返回0或者抛出异常,具体取决于需求。
    return 0;
}

代码解释:

  1. 初始化两个布尔变量 hasOne 和 hasTwo,分别用于记录列表中是否包含 '1' 和 '2'。
  2. 使用 foreach 循环遍历列表中的每个元素。
  3. 如果元素等于 '1',则将 hasOne 设置为 true;如果元素等于 '2',则将 hasTwo 设置为 true。
  4. 循环结束后,根据 hasOne 和 hasTwo 的值进行判断:
    • 如果 hasOne 和 hasTwo 都为 true,则返回 3,表示列表中包含 '1' 和 '2'。
    • 如果 hasOne 为 true,hasTwo 为 false,则返回 1,表示列表中只包含 '1'。
    • 如果 hasOne 为 false,hasTwo 为 true,则返回 2,表示列表中只包含 '2'。
    • 如果 hasOne 和 hasTwo 都为 false,则返回 0,表示列表为空或既不包含 '1' 也不包含 '2'。

注意事项:

  • 此代码仅适用于包含字符串 '1' 和 '2' 的列表。
  • 如果需要处理其他情况,例如列表中包含其他字符串或非字符串类型,则需要修改代码逻辑。
  • 如果列表为空,返回 0 或者抛出异常,具体取决于实际需求。

优化建议:

  • 使用 HashSet 来存储列表中的元素,可以提高判断效率。
  • 使用 string.Equals 方法进行字符串比较,可以避免潜在的错误。
  • 可以将代码封装成一个独立的方法,以便于重复使用。
C# 判断 List<string> 是否全是 1 或 2 - 算法实现

原文地址: https://www.cveoy.top/t/topic/niMR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录