Strong Coders Community

Where the extreme coders hang out.
Welcome to Strong Coders Community Sign in | Join | Help Messenger
in Search

Skip.First and IsAscending

Last post 02-05-2007, 1:32 PM by JamesCurran . 0 replies.
Sort Posts: Previous Next
  •  02-05-2007, 1:32 PM 1724
    • JamesCurran is not online. Last active: Feb 10, 2007, 10:07 AM JamesCurran
    • Top 10 Contributor
      Male
    • Joined on 11-01-2006
    • Bloomfield, NJ, USA
    • Posts 82
    • Points 1,015
    • StrongCoders

    Skip.First and IsAscending

    I just wrote a new entry over on my blog about an adapter to allow you to skip the first item when doing a foreach loop, and oddly enough, just today, I found some code on someone else's blog that could be improved with it.  So, rather than just repeat what I said on my own blog, go read that first, and then I'll present a use for it.

    The code in question is from Patrick Steele's .NET Blog  on " Using Generics To See If A List Is Ordered."   His code goes like this:

    private static bool IsAscending(T[] values) where T : IComparable
    {
        for ( int i = 0; i < values.Length - 1; i++)
        {
            if (values[ i ].CompareTo(values[i + 1]) > 0)
                return false ;
        }

        return true ;
    }

    Now, dispite the fact that the title refers to a "list", the code itself actually is limited to arrays.  One comments suggested replacing the "T[] values" parameter with "IList values", which really would allow any list to be handled.

    However, I would rather see it open to any IEnumerable collection.  The problem is that IEnumerable objects don't necessarily have an indexer, and since we're looking at two values at once, an indexer is real handy.

    But, it can be done with an Enumerator, we just have to treat the first item as a special case --- but that's a problem for foreach.  Enter Skip.First.

    Now, this is going to be a bit confusing if you haven't read the article I cited above, so now's your chance to go back & read it.

    Done?  OK, here's my revised version:

    private static bool IsAscending(IEnumerable values) where T : IComparable
    {
        IEnumerator iter = values.GetEnumerator();
        if (iter.MoveNext())
        {
            T lower = iter.Current;     // Get the first item
            foreach (T higher in Skip.First(values))  // Get the rest of them, skipping the first.
            {
                if (lower.CompareTo(higher) > 0)
                    return false;
                lower = higher;
            }
        }
        return true;
    }

     


    Truth,
    James
    Filed under: .NET Generics
    • Post Points: 5
    • Alert the moderators

Powered by Community Server (Commercial Edition), by Telligent Systems