[WayBack] Spring Collections I have a list of elements, there are, for example, 100 of them. List : IList; I want to get 5 values greater than 10 and … – Jacek Laskowski – Google+
Q
I have a list of elements, there are, for example, 100 of them.
List : IList<Integer>;
I want to get 5 values greater than 10 and I do it like this:
result: = List.Where(ValueIsGreatThan10).Take(5);
Will the “work loop” be executed a minimum number of times and if, for example, the first 5 values in the list will be greater than 5, then only the five will be checked? Or maybe the Where()
loop will scan 100 elements, and Take()
will return the first 5 results?
A (by Stefan Glienke)
Where
and Take
are streaming operators and only execute as much as required.
Also the operations have deferred execution. So your statement does not materialize any collection yet. Only if you iterate it will.
They are designed after the operators in .NET so the table from [WayBack] Classification of Standard Query Operators by Manner of Execution (C#) | Microsoft Docs applies. If you find any difference please report it.
Example:
var
nums: IEnumerable<Integer>;
i: Integer;
begin
nums := TEnumerable.Range(1, 100).Where(
function(const i: Integer): Boolean
begin
Writeln('checking: ', i);
Result := i > 10;
end
).Take(5);
Writeln('query created');
for i in nums do
Writeln('got number: ', i);
end.
This code will print:
query created
checking: 1
checking: 2
checking: 3
checking: 4
checking: 5
checking: 6
checking: 7
checking: 8
checking: 9
checking: 10
checking: 11
got number: 11
checking: 12
got number: 12
checking: 13
got number: 13
checking: 14
got number: 14
checking: 15
got number: 15
–jeroen
Like this:
Like Loading...