views:

39

answers:

2

Hi folks,

i'm got a simple IEnumerable<foo> foos; This collection are some results from a db call.

I wish to make sure that each item in the list is ordered correctly. The Db either returns the results by

  • ordered by id, lowest to highest. eg. 1, 2, 3, 4,. ... etc.
  • ordered by date created, decrement (most recent, first).

Can this be done with a quick linq statement .. to check for this?

eg. Assert.IsTrue(.. insert linq statement here .. )

currently, i've got a for loop and remember the previous entry and check if the value of that, if there was a value. This feels ... cumbersome.

Any ideas?

+3  A: 

You could compare your collection to an ordered version:

CollectionAssert.AreEqual(foos.ToList(), foos.OrderBy(f => f.Id));

Or:

CollectionAssert.AreEqual(foos.ToList(), 
                          foos.OrderByDescending(f => f.DateCreated));
Andy White
@Andy White , wow - that is very interesting! I never knew there was a CollectionAssert class :) that's awesome! That said, When I tried to do your code, i didn't have to do a ToList() for the first parameter ... but for the second one i DID have to add a .ToList() to the end of that funct .. can you just confirm that, please?
Pure.Krome
Oh, whoops, IEnumerable doesn't have a ToList() method. There are a few different techniques to convert an IEnumerable to a List. You might be able to apply a no-op extension method call to get it into a format that can be converted to a List.
Andy White
+2  A: 

There is an extension method called SequenceEqual which will do that. However, there is also an assert method called CollectionAssert.AreEqual that compares two collections to ensure they have the same items in the same order.

Josh Einstein