I have a scenario where I have a list of objects with a datetime field in the object. I’m trying to find out if there is a way to use LINQ to group the list by sequential datetimes and return a subset of the list with the sequential datetimes as a range.
public virtual IList<LineItem> LineItems { get; set; }
...
public class LineItem
{
public virtual string Status { get; set; }
public virtual DateTime TransDate { get; set; }
...
}
So If I had 6 LineItems with Status = P for all and
TransDate = { 8/1/2011 , 8/2/2011 , 8/3/2011 , 8/5/2011 , 8/6/2011 , 8/9/2011 }
respectively, I’d like to return the following list:
{ (P, 8/1/2011-8/3/2011) , (P,8/5/2011-8/6/2011) , (P,8/9/2011) }
Any thoughts? I can do this with iterating through the list manually and checking the TransDate to see if it’s sequential, I am just looking for a more elegant (preferably LINQ) way of doing it. Thanks!
I would use a helper method like this:
And then:
(edit: cleaned it up slightly, my first version was silly.)