C# Collection - Order by an element (Rotate)

后端 未结 6 485
迷失自我
迷失自我 2021-01-23 17:05

I have an IEnumerable collection. Lets say it contains 5 points (in reality it is more like 2000)

I want to order this collection so that a spe

6条回答
  •  走了就别回头了
    2021-01-23 17:24

    The naive implementation using linq would be:

    IEnumerable x = new[] { 1, 2, 3, 4 };
    var tail = x.TakeWhile(i => i != 3);
    var head = x.SkipWhile(i => i != 3);
    var combined = head.Concat(tail); // is now 3, 4, 1, 2
    

    What happens here is that you perform twice the comparisons needed to get to your first element in the combined sequence. The solution is readable and compact but not very efficient. The solutions described by the other contributors may be more efficient since they use special data structures as arrays or lists.

提交回复
热议问题