.net - .NET How to check if a list is in numerical order (1-9)?
问题描述
I have a List, such as { 1, 2, 3, 4, 5 } or { 1, 2, 4 } or { 3, 4, 5 }. I need to check if the list is in numerical order with no skips. For example, { 1, 2, 3 } would be valid but { 1, 2, 4 } would not. The list may start with any number, end with any number, and contain any number of ints. Here's what I have, which seems to work but isn't very elegant. Is there a better or cleaner way to do this?
public bool ValidateList(List<int> list)
{
int previousInt = null;
foreach (var index in list)
{
if (previousInt == null)
{
previousInt = index;
continue;
}
if (index != previousInt + 1)
return false;
previousInt = index;
}
return true;
}
解决方案
LINQ 非常适合这种事情:
using System.Linq;
bool ValidateList(List<int> list)
{
var range = Enumerable.Range(list.First(), list.Count());
return Enumerable.SequenceEqual(range, list);
}
推荐阅读
- python - ModuleNotFoundError 但 pkg_resources 找到它
- floating-point - 有人可以解释从十进制到 IEE 754 Binary32 的转换吗?
- haskell - 避免预言机,或分离相同类型的预言机
- apache-storm - ActiveMQ Artemis 和代理 URI
- .net - 我的 EF Core FromSqlRaw 查询将奇怪的数据返回到我的数据存储库服务中的列表中。(在 Blazor 服务器应用中)
- android - Android 在特定频率上生成 Shepard Tone
- java - Spring Boot 计划任务未运行
- java - 遇到 java.lang.NullPointerException
- laravel - 不能在 Laravel 8 中使用遗留工厂
- python - Matlab中ndarray的访问属性