源自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();
        }
    }
}

 

 
posted @ 2013-04-17 17:32  TonyChan  阅读(344)  评论(0编辑  收藏  举报