Easiest way to Rotate a List in c#

后端 未结 16 3140
鱼传尺愫
鱼传尺愫 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:39

    It seems like some answerers have treated this as a chance to explore data structures. While those answers are informative and useful, they are not very Linq'ish.

    The Linq'ish approach is: You get an extension method which returns a lazy IEnumerable that knows how to build what you want. This method doesn't modify the source and should only allocate a copy of the source if necessary.

    public static IEnumerable> Rotate(this List source)
    {
      for(int i = 0; i < source.Count; i++)
      {
        yield return source.TakeFrom(i).Concat(source.TakeUntil(i));
      }
    }
    
      //similar to list.Skip(i-1), but using list's indexer access to reduce iterations
    public static IEnumerable TakeFrom(this List source, int index)
    {
      for(int i = index; i < source.Count; i++)
      {
        yield return source[i];
      }
    }
    
      //similar to list.Take(i), but using list's indexer access to reduce iterations    
    public static IEnumerable TakeUntil(this List source, int index)
    {
      for(int i = 0; i < index; i++)
      {
        yield return source[i];
      }
    }
    

    Used as:

    List myList = new List(){1, 2, 3, 4, 5};
    foreach(IEnumerable rotation in myList.Rotate())
    {
      //do something with that rotation
    }
    

提交回复
热议问题