2010-04-04 104 views
13

一個怎樣創建一個使用整數i的方法,並在指數i從當前位置移動List<T>的成員列表前面的列表的前面?移動列表的成員

+0

你正在嘗試對它進行分類,是嗎? – vittore 2010-04-04 19:26:27

+0

我需要對它進行排序嗎?我只想將索引i處的ONE成員移動到列表的前面..不需要移動其餘的部分 – Shonna 2010-04-04 19:27:23

+0

我會給你一個upvote,但是你沒有選擇明顯的答案。對不起:(。 – 2015-05-06 16:34:54

回答

25

List<T>類並不提供這樣的方法,但你可以編寫獲取項目的擴展方法,刪除它終於重新插入它:

static class ListExtensions 
{ 
    static void MoveItemAtIndexToFront<T>(this List<T> list, int index) 
    { 
     T item = list[index]; 
     list.RemoveAt(index); 
     list.Insert(0, item); 
    } 
} 
+0

不錯的擴展名。 – vittore 2010-04-04 19:31:39

+0

該方法的標題應該是這樣的: public void MoveToFront(int i) – Shonna 2010-04-04 19:31:55

+15

好吧,既然你知道簽名,我敢大膽宣稱這是作業。下一次 – 2010-04-04 19:34:54

4
var l = new List<DataItem>(); 
var temp = l[index]; 
l.RemoveAt(index); 
l.Insert(0, temp); 
2

試試這個

static List<int> idList = new List<int>() { 1, 2, 4, 5, 6, 8, 9 }; 

    private static void moveListItem(int index) 
    { 
     int getIndex = 0; 

     foreach (int item in idList) 
     { 
      Console.WriteLine(" Before Id List Value - {0} ,Index - {1} ", item.ToString(), getIndex); 
      getIndex++; 
     } 

     int value = idList[index]; 
     idList.RemoveAt(index); 
     idList.Insert(0, value); 

     Console.WriteLine(); 

     getIndex = 0; 
     foreach (int item in idList) 
     { 
      Console.WriteLine(" After Id List Value - {0} ,Index - {1} ", item.ToString(), getIndex); 
      getIndex++; 
     } 
    } 
7

到目前爲止,3個答案中的任何一個都能做到這一點,但我並不是想做一個RemoveAt和一個Insert操作,而是建議將每個項目從所需的位置向左移動一個位置,到列表的開頭。這樣你可以避免移動被移動物品右側的物品。

這是@ dtb答案的修改。

static class ListExtensions 
{ 
    static void MoveItemAtIndexToFront<T>(this List<T> list, int index) 
    { 
     T item = list[index]; 
     for (int i = index; i > 0; i--) 
      list[i] = list[i - 1]; 
     list[0] = item; 
    } 
} 
+0

對於擴展方法,這會更有意義,因爲它比dtb方法的平均速度更快。 – Groo 2015-09-14 08:54:05

+0

@Groo即使對於更大的列表,它總是更快嗎? – Coops 2016-04-05 12:59:49

+0

@CodeBlend:是的,對於更大列出差異會更明顯,雖然我不能聲稱你會注意到一個在實踐中的差異。理論上講,這個方法和dtb都是'O(n)',但是在dtb的答案中'list.RemoveAt'將首先移除該項目,然後將所有後續項目向後複製一次,然後'list.Insert(0,item) '會再次將索引項'0'插入,然後將所有項目向前複製1個位置。另一方面,Fede的方法只是向後掃描一次(交換次數等於'index')。 – Groo 2016-04-05 13:09:37

0

在白費口舌的風險:

那不是一個LinkedList更適合呢? 儘管你會失去隨機訪問功能,但在List開頭插入元素會更簡單(.AddFirst),並且效率更高。