Skip to content

Instantly share code, notes, and snippets.

@smallgeek
Created July 4, 2016 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smallgeek/fee353bfa9e47a034490c5b7aa5797de to your computer and use it in GitHub Desktop.
Save smallgeek/fee353bfa9e47a034490c5b7aa5797de to your computer and use it in GitHub Desktop.
<Extension>
Public Iterator Function ChunkBySumIf(Of T)(source As IEnumerable(Of T), selector As System.Func(Of T, Double), predicate As System.Func(Of Double, Boolean)) As IEnumerable(Of IEnumerable(Of T))
If source Is Nothing Then Throw New ArgumentNullException(NameOf(source))
If selector Is Nothing Then Throw New ArgumentNullException(NameOf(selector))
If predicate Is Nothing Then Throw New ArgumentNullException(NameOf(predicate))
Using enumerator = source.GetEnumerator()
Dim values As List(Of T) = Nothing
While enumerator.MoveNext
values = If(values, New List(Of T))
If predicate(values.Sum(selector) + selector(enumerator.Current)) Then
values.Add(enumerator.Current)
Else
Yield values.Hide()
values = New List(Of T)({enumerator.Current})
End If
End While
If values?.Count > 0 Then
Yield values
End If
End Using
End Function
<Extension>
Public Iterator Function Hide(Of T)(source As IEnumerable(Of T)) As IEnumerable(Of T)
If source Is Nothing Then Throw New ArgumentNullException(NameOf(source))
Using enumerator = source.GetEnumerator()
While enumerator.MoveNext
Yield enumerator.Current
End While
End Using
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment