C# 判断 List<string> 是否全是 1 或 2 - 算法实现
以下是实现代码:
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;
}
代码解释:
- 初始化两个布尔变量
hasOne和hasTwo,分别用于记录列表中是否包含 '1' 和 '2'。 - 使用
foreach循环遍历列表中的每个元素。 - 如果元素等于 '1',则将
hasOne设置为true;如果元素等于 '2',则将hasTwo设置为true。 - 循环结束后,根据
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方法进行字符串比较,可以避免潜在的错误。 - 可以将代码封装成一个独立的方法,以便于重复使用。
原文地址: https://www.cveoy.top/t/topic/niMR 著作权归作者所有。请勿转载和采集!