c# - 有没有办法使 Int 变量等于(==)存储在数组中的所有数字?
问题描述
好的,所以我是编码新手,我刚刚在这里开设了一个帐户以获得一些帮助。我的任务是编写一个应用程序,该应用程序将在控制台中打印 0-100 的数字。但不是“32、44 和 77”。我知道我可以做很多 If 语句,但我的问题是我是否可以将三个数字存储在一个数组中,然后说:
int numZero = 0;
int[] num = { 32, 44, 77 };
while (numZero <= 100)
{
Console.WriteLine(numZero);
numZero++;
// I know the num needs to have a value assigned. But can I make the "numZero" go through the three numbers in num?
if (numZero == num [])
{
numZero++;
}
感谢您的建议!
解决方案
您可以使用从 0 到 100 的 for 循环,并在循环中测试Exists()
数组中的索引是否不打印,否则打印。
您还可以使用 Linq 扩展方法Contains()
代替Array.Exists()
.
这样做你将有 3 行代码:
- 为了
- 如果!包含
- 打印(如果包含,你什么也不做)。
因此你可以试试这个:
using System.Linq;
int[] num = { 32, 44, 77 };
for ( int index = 0; index <= 100; index++ )
if ( !num.Contains(index) )
Console.WriteLine(index);
你也可以写:
foreach ( int index in Enumerable.Range(0, 101) )
if ( !num.Contains(index) )
Console.WriteLine(index);
使用Enumerable.Range
避免了操作索引和增量,因此代码更干净,更安全。
注意:如果 100 不包含更改<=
为<
,或使用Range(0, 100)
。
推荐阅读
- image-processing - 使用 GDAL 将 PNG 转换为 GeoTIFF
- javascript - .length 不适用于 Google Apps 脚本中的数组
- c# - @Viewbag 第一次使用时给出空值
- python - Python - 将文本链接转换为 html
- html - Angular:删除并重新添加图像时,它不会创建新请求,也不会遵守缓存控制标头
- c++ - 在 C++ 中使用迭代器逐个字符地比较字符串
- dax - 如何创建一个返回数据集中最新状态(非数字)的度量?
- node.js - 当前日期和当前日期+2天的Java脚本时刻日期计算
- rollup - 如何使用 Deno 在运行时编译汇总?
- c# - Microsoft.Data.SqlClient.SqlConnection 在调试/发布中工作,但在安装程序中失败