Preserving Order in LINQ Queries
When using LINQ operations on ordered arrays, it's crucial to maintain the array's original order. This article examines which operations preserve the array's order and those that alter or redefine it.
Preserving Order Absolutely
The following operations do not alter the array's order:
-
AsEnumerable: Converts an existing IEnumerable to another IEnumerable without affecting order.
-
Cast: Casts elements to a new type, preserving their sequence.
-
Concat: Appends two sequences together, maintaining the order of each sequence.
-
Select: Maps source elements to result elements without reordering.
-
ToArray: Converts the sequence to an array, preserving its order.
-
ToList: Converts the sequence to a list, retaining its order.
Preserving Order
These operations filter or add elements without reordering the array:
-
Distinct: Removes duplicate elements while preserving the order of the remaining elements.
-
Except: Returns the elements present in the source sequence but not in the specified sequence, preserving the source sequence's order.
-
Intersect: Returns the elements present in both sequences, preserving the order of both sequences.
-
OfType: Filters elements by type, preserving the order of matching elements.
-
Prepend: Adds an element to the beginning of the sequence (new in .NET 4.7.1).
-
Skip: Skips a specified number of elements from the start of the sequence, preserving the order of the remaining elements.
-
SkipWhile: Skips elements from the start of the sequence while a specified condition is true, preserving the order of the remaining elements.
-
Take: Returns a specified number of elements from the start of the sequence, preserving their order.
-
TakeWhile: Returns elements from the start of the sequence while a specified condition is true, preserving their order.
-
Where: Filters elements by a specified condition, preserving the order of matching elements.
-
Zip: Pairs elements from two sequences in a zipped sequence (new in .NET 4), maintaining the order of each sequence.
The above is the detailed content of Which LINQ Operations Preserve the Original Order of an Array?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn