zoukankan      html  css  js  c++  java
  • 源自StackOverflow:找到LIST中第一个降序成员,有助于对扩展方法、IEnumerable<T>、泛型的理解

    问题是有如一组List,需要找到第一个降序成员。

    问题提出者举了一个例子:

    1,2,2,3,3,4,4,5,5,
    4,<=this should be my output 4,3,3,2,2,1

    解决方法有很多,最简单的方法——逐成员遍历即可解决,但MarcinJuraszek采用了如下解决方法,综合了扩展方法、Enumerable<T>、泛型,对学习C#还是很有帮助和借鉴的。

    首先,针对了
    IEnumerable创建了一个扩展方法,使其可作用于IEnumerable。在扩展方法中,逐变量循环,找到符合前成员大于本成员的成员并返回IEnumerable。
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DescendingDemo
    {
        public static class ExtendClass
        {
            public static IEnumerable<TSource> Descending<TSource>(this IEnumerable<TSource> source)
                where TSource : IComparable<TSource>
            {
                using (var e = source.GetEnumerator())
                {
                    TSource previous;
                    if (e.MoveNext())
                    {
                        previous = e.Current;
                        while (e.MoveNext())
                        {
                            if (previous.CompareTo(e.Current) > 0)
                            {
                                yield return e.Current;
                            }
                            previous = e.Current;
                        }
                    }
                }
            }
        }
    }
    扩展方法创建完之后,直接使用就OK,如要找到第一个符合条件的成员,代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DescendingDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var input = new List<int>() { 1, 2, 3, 2, 4, 5, 6, 7, 8, 9 };
                var firstDescending = input.Descending().First();
                Console.WriteLine(firstDescending);
                Console.Read();
            }
        }
    }
    如需要返回所有的符合条件的成员,代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DescendingDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var input = new List<int>() { 1, 2, 3, 2, 4, 5, 6, 4, 8, 9 };
                var firstDescending = input.Descending();
    
                foreach (var val in firstDescending)
                {
                    Console.WriteLine(val);
                }
                Console.Read();
            }
        }
    }
     
  • 相关阅读:
    hibernate常用配置
    hibernate快速入门
    【转】Struts2中json插件的使用
    【转】Struts2解决表单重复提交问题
    OGNL表示式使用和值栈
    Python就是为了方便生活,比如看VIP电影
    使用python进行面部合成,比PS好用多了
    Python黑科技,教你学会Django系统错误监控
    Python这么厉害的么?一次爬完整站小说
    Linux优化不知如何下手?那你的看看这篇文章了
  • 原文地址:https://www.cnblogs.com/tonychan/p/3026699.html
Copyright © 2011-2022 走看看