views:

49

answers:

3

I made this. Is this the fastest way to find lastest DateTime of my collection of DateTimes?

I'm wondering if there is a method for what i'm doing inside the foreach, but even if there is, I can't see how it can be faster than what i all ready got.

List<StateLog> stateLogs = db.StateLog.Where(p => p.ProductID == product.ProductID).ToList();
                DateTime lastTimeStamp = DateTime.MinValue;

                foreach (var stateLog in stateLogs)
                {
                    int result = DateTime.Compare(lastTimeStamp, stateLog.TimeStamp);
                    if (result < 0)
                        lastTimeStamp = stateLog.TimeStamp; // sæt fordi timestamp er senere
                }
+1  A: 

You can compare the DateTimes using their overloaded operators:

foreach (var stateLog in db.StateLog.Where(p => p.ProductID == product.ProductID))
{
    if (lastTimeStamp < stateLog.TimeStamp)
        lastTimeStamp = stateLog.TimeStamp; // sæt fordi timestamp er senere
}
SLaks
Never underestimate the JIT compiler. It generates the *exact same code* in the Release build. Measure first.
Hans Passant
@Hans: How can the JITter optimize away a `Compare` call?
SLaks
It inlines it . Just like it inlines the operator< overload call.
Hans Passant
A: 
stateLogs.OrderByDescending(s=>s.TimeStamp).First(s=>s.TimeStamp)

Assumes that stateLogs is a non-empty collection.

Alternatively, a faster approach would be:

stateLogs.Max(s=>s.TimeStamp)

but I'm not sure it would outperform a handrolled loop.

spender
That's actually slower.
SLaks
Bah. Missed the "optimize" bit. Ignore me!
spender
Added a second approach.
spender
A: 

You can't make it faster, it is inherently an O(n) algorithm.

Hans Passant