Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Test if a list of dates is sorted 1

Status
Not open for further replies.

graabein

Programmer
Oct 9, 2002
186
NO
Hi, I'm pretty new to C# .Net 3.5 so go easy on me... I want to test if a list of dates is sorted.

I use LINQ to extract the DateTime field from a ObservableCollection<T> with either ToArray or ToList. I do this twice, with and without orderby clause.

The (simple?) problem is how do I compare the two lists?

Is this even the best way to attack this?

[elephant2]
graabein
 
Here is what I've got so far but it's probably not the best way to go about this. Suggestions are welcome!

Code:
private bool IsSorted(ObservableCollection<CustomEntity> coll)
{
    List<DateTime> unsorted = (from n in coll 
        where n.EventDateTime > DateTime.MinValue 
        select n.EventDateTime).ToList<DateTime>();
            
    List<DateTime> sorted = (from n in coll 
        where n.EventDateTime > DateTime.MinValue 
        orderby n.EventDateTime 
        select n.EventDateTime).ToList<DateTime>();

    for (int i = 0; i < unsorted.Count; i++)
    {
        if (unsorted[i] != sorted[i])
        {
            return false;
        }
    }
    return true;
}

[elephant2]
graabein
 
why do you need to know if the list is sorted. just sort the list.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
The user registers a list of dates. I want to see if they are in order.

[elephant2]
graabein
 
why not just sort them then? then they are in order. adding the complexity of knowing if they are sorted seems extraneous.

however, here is more condensed code.
Code:
private bool IsSorted(IEnumerable<CustomEntity> items)
{
   var previous = DateTime.MinValue;
   foreach(var item in items)
   {
      if(previous > item.EventDateTime) return false;
      previous = item.EventDateTime;
   }
   return true;
}

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Well I'm trying to write some tests to run on the code (not written yet). They're not registrations of the same thing, they're a series of events connected with a bigger operation so we need to know what happened when for later on. Some of these events have to be in the proper order.

Thanks for the code! It's so obvious I smacked my forehead. Been on holiday for too long I guess!

[elephant2]
graabein
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top