Preserving order with LINQ

前端 未结 6 1285
名媛妹妹
名媛妹妹 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:24

    I found a great answer in a similar question which references official documentation. To quote it:

    For Enumerable methods (LINQ to Objects, which applies to List), you can rely on the order of elements returned by Select, Where, or GroupBy. This is not the case for things that are inherently unordered like ToDictionary or Distinct.

    From Enumerable.GroupBy documentation:

    The IGrouping objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping. Elements in a grouping are yielded in the order they appear in source.

    This is not necessarily true for IQueryable extension methods (other LINQ providers).

    Source: Do LINQ's Enumerable Methods Maintain Relative Order of Elements?

提交回复
热议问题