Preserving order with LINQ

前端 未结 6 1397
名媛妹妹
名媛妹妹 2020-11-22 07:15

I use LINQ to Objects instructions on an ordered array. Which operations shouldn\'t I do to be sure the order of the array is not changed?

6条回答
  •  感动是毒
    2020-11-22 07:44

    If you are working on an array, it sounds like you are using LINQ-to-Objects, not SQL; can you confirm? Most LINQ operations don't re-order anything (the output will be in the same order as the input) - so don't apply another sort (OrderBy[Descending]/ThenBy[Descending]).

    [edit: as Jon put more clearly; LINQ generally creates a new sequence, leaving the original data alone]

    Note that pushing the data into a Dictionary<,> (ToDictionary) will scramble the data, as dictionary does not respect any particular sort order.

    But most common things (Select, Where, Skip, Take) should be fine.

提交回复
热议问题