2016-06-15 13 views
-2

我試着編寫一個測試,其中有兩個參數,一個名爲ints的List項目,以及一個名爲places的單個int,其中我將該列表向右旋轉指定的位置數。在C#中,如何將列表向右旋轉指定數量的地方?

這是我迄今爲止嘗試過的。

public void Test8(List<int> items, int places) 
    { 
     int a = 0; 

     if (a < items.Count) 
     { 
      a = a % items.Count; 
     } 

     int[] result = new int[items.Count]; 

     for (int i = 0; i < a; i++) 
     { 
      result[i] = items[items.Count - a + i]; 
     } 
     int j = 0; 
     for (int i = a; i < items.Count; i++) 
     { 
      result[i] = items[j]; 
      j++; 
     } 
+0

在這個例子沒有,你在哪裏使用參數「地方」 ......可以幫助發佈完整的方法 – Sorceri

+0

有意義的變量名可以幫助您。什麼是'a'?您將它初始化爲0,但立即檢查它是否大於'items.Count'。爲什麼?它不會發生,因爲'items.Count'不能小於0.你提到的'places'參數在哪裏使用? – itsme86

+0

下面是我沒有添加的部分代碼 - > public void Test8(列表項目,int位置) – ThunderCat

回答

0

您可以使用LINQ來做到這一點:

IEnumerable<T> RotateLeft<T>(IEnumerable<T> list, int places) 
{ 
    return list.Skip(places).Concat(list.Take(places)); 
} 

IEnumerable<T> RotateRight<T>(IEnumerable<T> list, int places) 
{ 
    return RotateLeft(list, list.Count() - places); 
} 
相關問題