是否可以使用 LINQ 检查列表中的所有数字是否单调递增?

2024-05-05

我感兴趣的是,在 LINQ 中是否有一种方法可以检查列表中的所有数字是否单调递增?

Example

List<double> list1 = new List<double>() { 1, 2, 3, 4 };
Debug.Assert(list1.IsIncreasingMonotonically() == true);

List<double> list2 = new List<double>() { 1, 2, 100, -5 };
Debug.Assert(list2.IsIncreasingMonotonically() == false);

我问的原因是我想知道将列表中的元素与其前一个元素进行比较的技术,这是我在使用 LINQ 时从未理解的。

已完成 C# 示例类

根据官方的回答@Servy下面是我现在使用的完整课程。它将扩展方法添加到您的项目中,以检查列表是否单调或严格单调增加/减少。我正在努力适应函数式编程风格,这是一种很好的学习方式。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyHelper
{
    /// <summary>
    /// Classes to check if a list is increasing or decreasing monotonically. See:
    /// http://stackoverflow.com/questions/14815356/is-it-possible-to-use-linq-to-check-if-all-numbers-in-a-list-are-increasing-mono#14815511
    /// Note the difference between strictly monotonic and monotonic, see:
    /// http://en.wikipedia.org/wiki/Monotonic_function
    /// </summary>
    public static class IsMonotonic
    {
        /// <summary>
        /// Returns true if the elements in the are increasing monotonically.
        /// </summary>
        /// <typeparam name="T">Type of elements in the list.</typeparam>
        /// <param name="list">List we are interested in.</param>
        /// <returns>True if all of the the elements in the list are increasing monotonically.</returns>
        public static bool IsIncreasingMonotonically<T>(this List<T> list) where T : IComparable
        {
            return list.Zip(list.Skip(1), (a, b) => a.CompareTo(b) <= 0).All(b => b);
        }

        /// <summary>
        /// Returns true if the elements in the are increasing strictly monotonically.
        /// </summary>
        /// <typeparam name="T">Type of elements in the list.</typeparam>
        /// <param name="list">List we are interested in.</param>
        /// <returns>True if all of the the elements in the list are increasing monotonically.</returns>
        public static bool IsIncreasingStrictlyMonotonically<T>(this List<T> list) where T : IComparable
        {
            return list.Zip(list.Skip(1), (a, b) => a.CompareTo(b) < 0).All(b => b);
        }

        /// <summary>
        /// Returns true if the elements in the are decreasing monotonically.
        /// </summary>
        /// <typeparam name="T">Type of elements in the list.</typeparam>
        /// <param name="list">List we are interested in.</param>
        /// <returns>True if all of the the elements in the list are decreasing monotonically.</returns>
        public static bool IsDecreasingMonotonically<T>(this List<T> list) where T : IComparable
        {
            return list.Zip(list.Skip(1), (a, b) => a.CompareTo(b) >= 0).All(b => b);
        }

        /// <summary>
        /// Returns true if the elements in the are decreasing strictly monotonically.
        /// </summary>
        /// <typeparam name="T">Type of elements in the list.</typeparam>
        /// <param name="list">List we are interested in.</param>
        /// <returns>True if all of the the elements in the list are decreasing strictly monotonically.</returns>
        public static bool IsDecreasingStrictlyMonotonically<T>(this List<T> list) where T : IComparable
        {
            return list.Zip(list.Skip(1), (a, b) => a.CompareTo(b) > 0).All(b => b);
        }

        /// <summary>
        /// Returns true if the elements in the are increasing monotonically.
        /// </summary>
        /// <typeparam name="T">Type of elements in the list.</typeparam>
        /// <param name="list">List we are interested in.</param>
        /// <returns>True if all of the the elements in the list are increasing monotonically.</returns>
        public static bool IsIncreasingMonotonicallyBy<T>(this List<T> list, Func<T> x) where T : IComparable
        {
            return list.Zip(list.Skip(1), (a, b) => a.CompareTo(b) <= 0).All(b => b);
        }

        public static void UnitTest()
        {
            {
                List<double> list = new List<double>() { 1, 2, 3, 4 };
                Debug.Assert(list.IsIncreasingMonotonically<double>() == true);
                Debug.Assert(list.IsIncreasingStrictlyMonotonically<double>() == true);
                Debug.Assert(list.IsDecreasingMonotonically<double>() == false);
                Debug.Assert(list.IsDecreasingStrictlyMonotonically<double>() == false);
            }

            {
                List<double> list = new List<double>() { 1, 2, 100, -5 };
                Debug.Assert(list.IsIncreasingMonotonically() == false);
                Debug.Assert(list.IsIncreasingStrictlyMonotonically() == false);
                Debug.Assert(list.IsDecreasingMonotonically() == false);
                Debug.Assert(list.IsDecreasingStrictlyMonotonically() == false);
            }

            {
                List<double> list = new List<double>() {1, 1, 2, 2, 3, 3, 4, 4};
                Debug.Assert(list.IsIncreasingMonotonically() == true);
                Debug.Assert(list.IsIncreasingStrictlyMonotonically<double>() == false);
                Debug.Assert(list.IsDecreasingMonotonically() == false);
                Debug.Assert(list.IsDecreasingStrictlyMonotonically() == false);
            }

            {
                List<double> list = new List<double>() { 4, 3, 2, 1 };
                Debug.Assert(list.IsIncreasingMonotonically() == false);
                Debug.Assert(list.IsIncreasingStrictlyMonotonically<double>() == false);
                Debug.Assert(list.IsDecreasingMonotonically() == true);
                Debug.Assert(list.IsDecreasingStrictlyMonotonically() == true);
            }

            {
                List<double> list = new List<double>() { 4, 4, 3, 3, 2, 2, 1, 1 };
                Debug.Assert(list.IsIncreasingMonotonically() == false);
                Debug.Assert(list.IsIncreasingStrictlyMonotonically<double>() == false);
                Debug.Assert(list.IsDecreasingMonotonically() == true);
                Debug.Assert(list.IsDecreasingStrictlyMonotonically() == false);
            }
        }
    }
}

public static bool IsIncreasingMontonically<T>(List<T> list) 
    where T : IComparable
{
    return list.Zip(list.Skip(1), (a, b) => a.CompareTo(b) <= 0)
        .All(b => b);
}

请注意,这会迭代序列两次。为一个List,这根本不是问题,对于IEnumerable or IQueryable,这可能会很糟糕,所以在改变之前要小心List<T> to IEnumerable<T>.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以使用 LINQ 检查列表中的所有数字是否单调递增? 的相关文章

  • UML类图:抽象方法和属性是这样写的吗?

    当我第一次为一个小型 C 项目创建 uml 类图时 我在属性方面遇到了一些麻烦 最后我只是将属性添加为变量 lt
  • linux perf:如何解释和查找热点

    我尝试了linux perf https perf wiki kernel org index php Main Page今天很实用 但在解释其结果时遇到了困难 我习惯了 valgrind 的 callgrind 这当然是与基于采样的 pe
  • 如何在列表框项目之间画一条线

    我希望能够用水平线分隔列表框中的每个项目 这只是我用于绘制项目的一些代码 private void symptomsList DrawItem object sender System Windows Forms DrawItemEvent
  • C++ 子字符串返回错误结果

    我有这个字符串 std string date 20121020 我正在做 std cout lt lt Date lt lt date lt lt n std cout lt lt Year lt lt date substr 0 4 l
  • 如何忽略“有符号和无符号整数表达式之间的比较”?

    谁能告诉我必须使用哪个标志才能使 gcc 忽略 有符号和无符号整数表达式之间的比较 警告消息 gcc Wno sign compare 但你确实应该修复它警告你的比较
  • 将布尔参数传递给 SQL Server 存储过程

    我早些时候问过这个问题 我以为我找到了问题所在 但我没有 我在将布尔参数传递给存储过程时遇到问题 这是我的 C 代码 public bool upload false protected void showDate object sende
  • .Net应用程序设置路径

    默认情况下 Windows 应用程序设置保存在该目录中 USERPROFILE Local Settings Application Data
  • 指针问题(仅在发布版本中)

    不确定如何描述这一点 但我在这里 由于某种原因 当尝试创建我的游戏的发布版本进行测试时 它的敌人创建方面不起作用 Enemies e level1 3 e level1 0 Enemies sdlLib 500 2 3 128 250 32
  • 在 Visual Studio 2008 上设置预调试事件

    我想在 Visual Studio 中开始调试程序之前运行一个任务 我每次调试程序时都需要运行此任务 因此构建后事件还不够好 我查看了设置的 调试 选项卡 但没有这样的选项 有什么办法可以做到这一点吗 你唯一可以尝试的 IMO 就是尝试Co
  • 如何将图像和 POST 数据上传到 Azure 移动服务 ApiController 终结点?

    我正在尝试上传图片and POST表单数据 尽管理想情况下我希望它是json 到我的端点Azure 移动服务应用 我有ApiController method HttpPost Route api upload databaseId sea
  • 在.rdlc报告的底部设置一个文本框

    我在 rdlc 报告中使用 tablix 有一个文本框 其中包含文本 签名 我想将此文本框放置在报告最后一页的底部 就在页脚之前 我已经用谷歌搜索了这个解决方案 但没有找到满意的结果 我的环境是VS2010 framework 4 0 有什
  • C 预处理器库

    我的任务是开发源分析工具C程序 并且我需要在分析本身之前预处理代码 我想知道什么是最好的图书馆 我需要一些重量轻 便于携带的东西 与其推出自己的 为什么不使用cpp这是的一部分gcc suite http gcc gnu org onlin
  • 如果使用 SingleOrDefault() 并在数字列表中搜索不在列表中的数字,如何返回 null?

    使用查询正数列表时SingleOrDefault 当在列表中找不到数字时 如何返回 null 或像 1 这样的自定义值 而不是类型的默认值 在本例中为 0 你可以使用 var first theIntegers Cast
  • Web API - 访问 DbContext 类中的 HttpContext

    在我的 C Web API 应用程序中 我添加了CreatedDate and CreatedBy所有表中的列 现在 每当在任何表中添加新记录时 我想填充这些列 为此目的我已经覆盖SaveChanges and SaveChangesAsy
  • 将自定义元数据添加到 jpeg 文件

    我正在开发一个图像处理项目 C 我需要在处理完成后将自定义元数据写入 jpeg 文件 我怎样才能做到这一点 有没有可用的图书馆可以做到这一点 如果您正在谈论 EXIF 元数据 您可能需要查看exiv2 http www exiv2 org
  • 当操作繁忙时,表单不执行任何操作(冻结)

    我有一个使用 C 的 WinForms 应用程序 我尝试从文件中读取一些数据并将其插入数据表中 当此操作很忙时 我的表单冻结并且无法移动它 有谁知道我该如何解决这个问题 这可能是因为您在 UI 线程上执行了操作 将文件和数据库操作移至另一个
  • 将 unsigned char * (uint8_t *) 转换为 const char *

    我有一个带有 uint8 t 参数的函数 uint8 t ihex decode uint8 t in size t len uint8 t out uint8 t i hn ln for i 0 i lt len i 2 hn in i
  • 为什么 C# Math.Ceiling 向下舍入?

    我今天过得很艰难 但有些事情不太对劲 在我的 C 代码中 我有这样的内容 Math Ceiling decimal this TotalRecordCount this PageSize Where int TotalRecordCount
  • mysql-connector-c++ - “get_driver_instance”不是“sql::mysql”的成员

    我是 C 的初学者 我认为学习的唯一方法就是接触一些代码 我正在尝试构建一个连接到 mysql 数据库的程序 我在 Linux 上使用 g 没有想法 我运行 make 这是我的错误 hello cpp 38 error get driver
  • C 中的异或运算符

    在进行按位操作时 我在确定何时使用 XOR 运算符时遇到一些困难 按位与和或非常简单 当您想要屏蔽位时 请使用按位 AND 常见用例是 IP 寻址和子网掩码 当您想要打开位时 请使用包含或 然而 XOR 总是让我明白 我觉得如果在面试中被问

随机推荐