Easiest way to Rotate a List in c#

后端 未结 16 3196
鱼传尺愫
鱼传尺愫 2020-12-01 07:06

Lists say I have a list List {1,2,3,4,5}

Rotate means:

=> {2,3,4,5,1} => {3,4,5,1,2} => {4,5,1,2,3}
16条回答
  •  一个人的身影
    2020-12-01 07:40

    How about this:

    var output = input.Skip(rot)
                      .Take(input.Count - rot)
                      .Concat(input.Take(rot))
                      .ToList();
    

    Where rot is the number of spots to rotate - which must be less than the number of elements in the input list.

    As @cadrell0 answer shows if this is all you do with your list, you should use a queue instead of a list.

提交回复
热议问题