Jump to content
Epo

Spring4D GroupBy First question

Recommended Posts

Hi,

In testing the function TEnumerable.GroupBy<T, TKey>(const source: IEnumerable<T>;  const keySelector: Func<T, TKey>): IEnumerable<IGrouping<TKey, T>> in
Spring Version Dev 2021/03/24 and Version 1.2.4, I find that a noticeable difference is present if I am not mistaken. The 3rd listbox (in the associated example) does not have the elements in the same order (and is even incorrect in the dev version- maybe because defered execution) depending on the version. In version 1.2.4, the order is "stable", which is an interesting property from my point of view. Will the behavior of the Dev version be the one adopted in the next version?

 

Thanks,

Eddy

ITreeData.zip

Share this post


Link to post

The culprit here is a different one: in 1.2.4 Shuffled caused a shuffle of the input sequence when being called while 2.0 does it every time when the enumerator is being used (internally or externally)

ElementAt for example does it - that means during your loop to print items to ListBox2 they are reshuffled every time and then the nth element is being picked by MoveNext n times.

And then again the shuffle is triggerd one time for the iteration being done by GroupBy.

 

This follows the implementation in MoreLinq where this was taken from originally.

 

If you want to shuffle but reuse the order then either do TCollections.CreateList(source.Shuffled) or TCollections.CreateList and then call Shuffle on that list.

Also I advice against using index based loops and ElementAt on IEnumerable - this will be O(n²) as many sequences are lazy evaluated and cause enumeration every time you call ElementAt.

 

When you fix this you will notice the output of GroupBy between 1.2.4 and 2.0 is exactly the same -> ordered by the appearance of the items in the source.

Edited by Stefan Glienke

Share this post


Link to post

Effectively, not what I want. I thought that this would be a nice (and efficient) solution to associate the result of GroupBy with a VirtualStringTree but from what you write, this is not the case.

Thanks for the help and ...Spring4D, Stefan.

Share this post


Link to post

The idea is to link nicely a struct to a VStringTree with multiple levels (2/3). To connect the OnGetText to it, the VST gives a node (with an index and parent..Index you known it ).  As you write the ElementAt is not very efficient. I suppose that it is better to use a list and some TFunc<> to filter ("GroupBy") one for each key level.  And Spring4D has everything you need to do it..

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×