I have a troublesome query to write. I’m currently writing some nasty for loops to solve it, but I’m curious to know if Linq can do it for me.
I have:
struct TheStruct
{
public DateTime date {get; set;} //(time portion will always be 12 am)
public decimal A {get; set;}
public decimal B {get; set;}
}
and a list that contains these structs. Let’s say it’s ordered this way:
List<TheStruct> orderedList = unorderedList.OrderBy(x => x.date).ToList();
If you put the orderedList struct dates in a set they will always be contiguous with respect to the day.. that is if the latest date in the list was 2011/01/31, and the earliest date in the list was 2011/01/01, then you’d find that the list would contain 31 items, one for each date in January.
Ok, so what I want to do is group the list items such that:
- Each item in a group must contain the same Decimal A value and the same Decimal B value
- The date values in a group must form a set of contiguous dates, if the date values were in order
- If you summed up the sums of items in each group, the total would equal the number of items in the original list (or you could say a struct with a particular date can’t belong to more than one group)
Any Linq masters know how to do this one?
Thanks!
You can group adjacent items in a sequence using the GroupAdjacent Extension Method (see below):
Example:
Extension Method: