using System;
using System.Collections.Generic;
using System.Linq;
public class DevicePosition
{
// stub
public DateTime Time;
}
public class Foo
{
// this should be IEnumerable.
private IEnumerator<DevicePosition> ValidPositions()
{
// stub
return null;
}
public bool FindRecentRepresentatives(
int milliseconds,
out DevicePosition current,
out DevicePosition previous)
{
if (milliseconds <= 0) {
throw new ArgumentOutOfRangeException ("milliseconds");
}
current = null;
previous = null;
IEnumerator<DevicePosition> valids = ValidPositions ();
valids.MoveNext ();
current = valids.Current;
if (current != null) {
long minTime = current.Time.Ticks - TimeSpan.FromMilliseconds (milliseconds).Ticks;
// this is the difficult part:
while (valids.MoveNext ()) {
if (valids.Current.Time.Ticks < minTime) {
break;
}
previous = valids.Current;
}
}
return (current != null) && (previous != null);
}
}
Refactorings
No refactoring yet !
Cohen
April 17, 2009, April 17, 2009 16:05, permalink
This might be a dumb proposal but why not include the condition from the if into the while clause?
while (valids.MoveNext () && valids.Current.Time.Ticks > minTime) {
previous = valids.Current;
}
Moonshield
April 22, 2009, April 22, 2009 04:47, permalink
I haven't fully tested yet but you could do something similar to this. I changed the IEnumerator for IEnumerable as your comment was already suggesting it..
// this should be IEnumerable.
private IEnumerable<DevicePosition> ValidPositions()
{
// stub
return null;
}
public bool FindRecentRepresentatives(int milliseconds, out DevicePosition current, out DevicePosition previous)
{
if (milliseconds <= 0)
throw new ArgumentOutOfRangeException("milliseconds");
var aValidPositions = ValidPositions();
current = aValidPositions.First();
previous = aValidPositions.Last(x => x.Time.Ticks > (x.Time.Ticks - TimeSpan.FromMilliseconds(milliseconds).Ticks));
return (current != null) && (previous != null);
}
mafutrct
April 27, 2009, April 27, 2009 11:54, permalink
Thanks a lot to both of you, that was the idea I was looking for. :)
software development london
August 19, 2009, August 19, 2009 17:02, permalink
Quite inspiring,
it's quite intersting to know that writing with c#3.5 is this much cleaner ( I mean the line of code are less)
Thanks
First of all, i'm new to this site, so please point out mistakes of this submit.
I'm trying to improve some older code that was written for .net 3.0 with features found in 3.5. The current version works fine, but it seems like it takes more lines than actually needed.
Purpose of this function is to find two values in a list. One of them is simply the first value.
The second value is supposed to be that last value that lies within a time range. However, not the last value in the whole list, but the last satisfying value just before the first not-satisfying value.
Sadly, I found no nice way to refactor the while loop. Everything else (except for that while) is not much of a problem.