Let's take a class called Cls
:
public class Cls
{
public int SequenceNumber { get; set; }
public int Value { get; set; }
}
Now, let's populate some collection with following elements:
Sequence Number Value ======== ===== 1 9 2 9 3 15 4 15 5 15 6 30 7 9
What I need to do, is to enumerate over Sequence Numbers and check if the next element has the same value. If yes, values are aggregated and so, desired output is as following:
Sequence Sequence Number Number From To Value ======== ======== ===== 1 2 9 3 5 15 6 6 30 7 7 9
How can I perform this operation using LINQ query?
You can use Linq's
GroupBy
in a modified version which groups only if the two items are adjacent, then it's easy as:DEMO
Result:
This is the extension method to to group adjacent items:
and the class used: