首页 > 解决方案 > .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;
}

标签: .netintegernumbers

解决方案


LINQ 非常适合这种事情:

using System.Linq;

bool ValidateList(List<int> list)
{
    var range = Enumerable.Range(list.First(), list.Count());
    return Enumerable.SequenceEqual(range, list);
}

推荐阅读