Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve order of values with linq and ToLookup()

Tags:

While I'm pretty certain that the keys are unordered when returned from linq's ToLookup method, Is the order of values preserved? I can't find any documentation that says one way or the other.

like image 823
Dan Avatar asked Jul 27 '09 19:07

Dan


People also ask

Does ToLookup preserve order?

The current implementation of ToLookup() does indeed preserve the order of the values (check the implementation of Lookup<TKey,TElement>.

Does LINQ preserve order?

Therefore, by default, PLINQ does not preserve the order of the source sequence. In this regard, PLINQ resembles LINQ to SQL, but is unlike LINQ to Objects, which does preserve ordering.

What is ToLookup in LINQ?

ToLookup operator in LINQ is an extension method, and it is used to extract a set of key/value pairs from the source. Here, each element in the resultant collection is a generic Lookup object. Lookup object holds the Key and subsequence items that matched with the Key.

Does group by preserve order?

Groupby preserves the order of rows within each group. When calling apply, add group keys to index to identify pieces. Reduce the dimensionality of the return type if possible, otherwise return a consistent type.


2 Answers

The current implementation of ToLookup() does indeed preserve the order of the values (check the implementation of Lookup<TKey,TElement>.Grouping<TKey,TElement>.Add()), but I do not believe it is guaranteed to stay that way. To guarantee ordering, your best bet is probably to include the element's original index, perhaps using Select's with-index overload, and then sort again.

like image 85
dahlbyk Avatar answered Oct 23 '22 13:10

dahlbyk


Yes. According to the documentation:

The values within each group are in the same order as in source.

like image 35
StriplingWarrior Avatar answered Oct 23 '22 13:10

StriplingWarrior