
LINQ and array order: Detailed explanation of which methods keep order and which methods do not keep
When using LINQ to Objects operations on sorted arrays, be sure to avoid operations that break the order of the original array. The following analysis will guide you:
Method to absolutely keep order:
]
- AsEnumerable:
]
- Cast:
- Concat:
- Select:
- ToArray:
- ToList:
These methods map source elements to result elements while maintaining order.
Usually keep order:
]
- Distinct: Filter duplicate elements.
- Except: Filter out elements that exist in another sequence.
- Intersect: Filter elements that exist together in multiple sequences.
- OfType: Filter elements based on type.
- Prepend (New in .NET 4.7.1): Add the specified value before the element.
- Skip: Skip the specified number of elements.
- SkipWhile: Skip element until the specified condition is met.
- Take: Returns the specified number of elements.
- TakeWhile: Returns the element until the specified condition is met.
- Where: Filter elements based on predicate.
- Zip (New in .NET 4): Merge corresponding elements in multiple sequences.
Methods to destroy the order:
- ToDictionary: Convert elements to dictionary, resulting in unordered collections.
- ToLookup: Convert elements to lookup tables, resulting in unordered collections.
Method to explicitly redefine order:
]
- OrderBy: Sort elements in ascending order.
- OrderByDescending: Sort elements in descending order.
- Reverse: Reverse:
Reverse element order. -
ThenBy:
Sort elements by another attribute, keeping in the original order. -
ThenByDescending:
Sort elements in descending order of another attribute, keeping in the original order.
Method of redefining order according to rules:
]
-
GroupBy:
Key grouping elements to maintain the order of elements in each group. -
GroupJoin:
Maintains the order of external sources and elements within each group based on key connections. -
Join:
Connect elements based on keys to maintain the order of internal and external elements. -
SelectMany:
Generates a series of sequences that combine elements in each sequence in an unpredictable order. -
Union:
Merge multiple sequences and generate elements in the order of the sequence provided.
By understanding these nuances, you can keep the required order of the array while performing LINQ operations, ensuring its integrity for further processing or display.