Skip to content

Commit 5223efb

Browse files
committed
refactored TEnumerableBase<T>.Sum (resolves #369)
1 parent 94de12a commit 5223efb

File tree

1 file changed

+20
-22
lines changed

1 file changed

+20
-22
lines changed

Source/Base/Collections/Spring.Collections.Base.pas

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1716,30 +1716,28 @@ function TEnumerableBase<T>.SkipWhile(
17161716
end;
17171717

17181718
function TEnumerableBase<T>.Sum: T;
1719-
var
1720-
enumerator: IEnumerator<T>;
1721-
item: T;
17221719
begin
1723-
Result := Default(T);
1724-
enumerator := IEnumerable<T>(this).GetEnumerator;
1725-
while enumerator.MoveNext do
1726-
begin
1727-
{$IFDEF RSP31615}
1728-
if IsManagedType(T) then
1729-
IEnumeratorInternal(enumerator).GetCurrent(item)
1730-
else
1720+
if TypeInfo(T) = TypeInfo(Integer) then
1721+
PInteger(@Result)^ := TEnumerable.Sum(IEnumerable<Integer>(this))
1722+
else if TypeInfo(T) = TypeInfo(Int64) then
1723+
PInt64(@Result)^ := TEnumerable.Sum(IEnumerable<Int64>(this))
1724+
else if TypeInfo(T) = TypeInfo(NativeInt) then
1725+
{$IFDEF CPU32BITS}
1726+
PInteger(@Result)^ := TEnumerable.Sum(IEnumerable<Integer>(this))
1727+
{$ELSE}
1728+
PInt64(@Result)^ := TEnumerable.Sum(IEnumerable<Int64>(this))
17311729
{$ENDIF}
1732-
item := enumerator.Current;
1733-
case TType.Kind<T> of
1734-
tkInteger: PInteger(@Result)^ := PInteger(@Result)^ + PInteger(@item)^;
1735-
tkInt64: PInt64(@Result)^ := PInt64(@Result)^ + PInt64(@item)^;
1736-
tkFloat:
1737-
case GetTypeData(TypeInfo(T)).FloatType of
1738-
ftSingle: PSingle(@Result)^ := PSingle(@Result)^ + PSingle(@item)^;
1739-
ftDouble: PDouble(@Result)^ := PDouble(@Result)^ + PDouble(@item)^;
1740-
end;
1741-
end;
1742-
end;
1730+
else if TypeInfo(T) = TypeInfo(System.Single) then
1731+
PSingle(@Result)^ := TEnumerable.Sum(IEnumerable<System.Single>(this))
1732+
else if TypeInfo(T) = TypeInfo(Double) then
1733+
PDouble(@Result)^ := TEnumerable.Sum(IEnumerable<Double>(this))
1734+
else if TypeInfo(T) = TypeInfo(Currency) then
1735+
PCurrency(@Result)^ := TEnumerable.Sum(IEnumerable<Currency>(this))
1736+
else
1737+
// if T is not of any of the above types this way of calling Sum is not supported
1738+
// consider using TEnumerable.Sum with a selector function to turn the values
1739+
// to any of the supported types for calculating the sum
1740+
RaiseHelper.NotSupported;
17431741
end;
17441742

17451743
function TEnumerableBase<T>.Take(count: Integer): IEnumerable<T>;

0 commit comments

Comments
 (0)