Mohanraja - 1 year ago 58
C# Question

# How to find continuous segment pair in given list of integers (Functionally not imerative)?

I have List of integers like {1,2,3,5,8,9,10}, I need the following result
[1,3],[5,5],[8,10]

I written the solution using imperative style, but I want a solution which align with functional programming.

My imperative solution:

``````    public static List<ContinuousNotificationSegment> ConvertToNotificationSegment(this List<NotificationDTO> input)
{
var sortedNotificationList = input.Select(n => n.ID).ToList();

long continuousSegmentStart = 0, continuousSegmentEnd = 0;

for (int i = 0; i < sortedNotificationList.Count; i++)
{
{
continuousSegmentStart = continuousSegmentStart == 0 ? sortedNotificationList[i] : continuousSegmentStart;
}
else
{

{
MinNotificationId = continuousSegmentStart == 0 ? continuousSegmentEnd : continuousSegmentStart,
});

continuousSegmentStart = 0;
}
}

return continuousSegments;
}

private static bool IsContinuous(long prevValue, long nextValue)
{
return nextValue - prevValue == 1;
}
``````

``````var input = new[] { 1, 2, 3, 5, 8, 9, 10 };

var result =
input
.Skip(1)
.Aggregate(
input.Take(1).Select(x => new { start = x, end = x }).ToList(),
(a, x) =>
{
var last = a.Last();
if (last.end + 1 == x)
{
a[a.Count - 1] = new { start = last.start, end = x };
}
else
{
a.Add(new { start = x, end = x });
}
return a;
});
``````

That works. I get:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download