Example, I have the following interface and classes:
public interface IRole {
DateTime Since {get;}
DateTime Until {get;}
}
public class Manager : IRole {
public DateTime Since {get; private set;}
public DateTime Until {get; private set;}
}
public class Employee : IRole {
public DateTime Since {get; private set;}
public DateTime Until {get; private set;}
}
public class Ceo: IRole {
public DateTime Since {get; private set;}
public DateTime Until {get; private set;}
}
If a generic list contains the following items:
list[0]=new Manager();
list[1]=new Manager();
list[2]=new Employee();
list[3]=new Manager();
list[4]=new Ceo();
list[5]=new Ceo();
And I shall merge the same types, combine the Since/Until and shrink the items in list, so the output becomes:
newList[0]=new Manager() //(Since is from list[0], Until is from list[1])
newList[1]=new Employee() //(list[2])
newList[2]=new Manager() //(list[3])
newList[3]=new Ceo() //(Since is from list[4], Until is from list[5])
Please make sure you understand the question before answering as I have a history of being ambigous and I don’t want to upset people. So please comment if you feel the “requirement” isn’t clear.
My way is kind of dumb:
for each item in list
the current item shall always be merged into the previous item
check if current item has the same type as the previous item
get last item from newList and merge last item with current item
I was just wondering there must be a better solution.
Updated:
I just realize my “dumb solution” won’t cover cases like more than 2 continuous items with the same type.
Example:
list[0]=new Manager();
list[1]=new Manager();
list[2]=new Employee();
list[3]=new Manager();
list[4]=new Ceo();
list[5]=new Ceo();
list[6]=new Ceo();
I wrote a blog post about this :-).
It feels almost like
group byexcept, you don’t want to group elements globally. Instead, you only want to group elements that are adjacent in the input list. The blog post provides some code that allows you to change the meaning ofgroup byin the LINQ query, so you could write just:The call to
WithAdjacentGroupingspecifes that grouping should only group adjacent elements. Then we can collect adjacent groups of persons by type (usingGetType().Nameas the key).Finally, we return a collection that contains the name of the type (e.g. “Ceo”) and two times –
SinceandUntilthat are calculated as minimal/maximal time from the collected group.WithAdjacentGrouping