c# - 如何检查我是否在 if 语句中越界?
问题描述
我有一个循环试图对数据进行排序和组织。
for (int a = 0; a < Combos.Count; a++)
{
//Largest to smallest
if (Combos.Count - a >= 1)
{
if (scores[a + 1] != null)
{
Combos.Add(Combos[a]);
Combos.RemoveAt(a);
scores.Add(scores[a]);
scores.RemoveAt(a);
}
}
}
我想在嵌套if语句有效时执行它,在java中我通常使用== null,但这似乎不起作用。是否有我可以使用的异常或检查它是否超出范围的东西?
解决方案
而不是这个
if (scores[a + 1] != null)
您检查Count
(列表)或Length
(数组):
if (a + 1 <= scores.Count)
不清楚您要在这里做什么,但我想有更简单的方法
//Largest to smallest
例如使用 LINQ:
var orderedCombos = Combos.Zip(scores, (c, s) => new{ Combo = c, Score = s})
.OrderByDescending(x => x.Score)
.Select(x => x.Combo)
.ToList();
(但你真的应该将这两个信息存储在同一个类中,或者至少不要通过索引链接)
推荐阅读
- c# - ASP.Net Core Web API 如何调用存储过程并返回 1 个结果对象
- sql - 为 BigQuery 中的每一天定义虚拟列
- javascript - 节点 js 和图表 js 的 ejs 对象存在问题
- ios - 如何在 Firestore 中获取文档密钥
- ruby-on-rails - 使用 mysql 数据库设计可跟踪的迁移错误
- amazon-web-services - 有没有其他方法可以使用 docker 容器安装亚马逊 S3 存储桶
- php - 将 nextjs 应用程序转换为 wordpress 简码
- node.js - 如何使用 tsserver + JSDoc 扩展 express.Request?
- c# - .NET 中所有可能引发的 XmlSchemaExceptions 的列表在哪里?
- javascript - 将状态从孩子传递给父母