views:

42

answers:

2

I have a IEnumerable collection of objects. The objects have a field LastedUpdated which is a DateTime field.

I want to filter the collection, given a timestamp that I have, to return the record in the collection with that timestamp and the "next record" in time (based on this field) because I then want to have some code do a "diff" between the two different records to show what has changed.

I am trying to figure out the best way to take a collection and do this filtering possibly using LINQ

Any suggestions?

A: 

This isn't the most efficient, but unless you think performance is an issue, I'd consider it clearest.

var objsByDate = objects.OrderBy(x => x.LastedUpdated).ToArray();
int matchIdx = Array.FindIndex(objsByDate, x => x.LastedUpdated == timestamp);

if (matchIdx >= 0)
{
    var match = recentObjects[matchIdx];
    var next = recentObjects[matchIdx + 1]; // assuming it exists
}
mquander
@mquander - i would like it to be as fast as possible as I am hovering over some text on a webpage and i am doing an ajax call to populate a tooltip.
ooo
@ooo: Unless there are at least thousands of objects, this will be imperceptibly fast. If there are indeed thousands or more objects, I suggest that you consider using a sorted data structure, and also suggest that you use binary search to find the right ones instead of a linear search. I'm not sure what you mean by indexing not working -- this code runs verbatim for me.
mquander
@mquander - indexing doesn't seem to work on IEnumerable<>
ooo
+3  A: 

How about this?

var results = (from o in objects
  where o.lastupdated >= tstamp
  orderby o.lastupdated
  select o).Take(2);
Tahbaza
That returns a result even if nothing actually matches the timestamp, which may or may not be OK.
mquander
@mquander - just a fyi, in my case there is always going to be a match
ooo
@Tahbaza - this above doesn't compile (has to be orderby)
ooo
@ooo: removed the space
Tahbaza