2010-08-06 85 views

回答

28
var itemsOneThroughTwenty = myList.Take(20); 
var itemsFiveThroughTwenty = myList.Skip(5).Take(15); 
+6

請注意,這些Linq擴展實際上創建了一個IEnumerable <>,它在N項後停止,而不是創建新的數組/列表。 (這是通過對變量類型使用'var'隱藏的,如果截斷後的代碼迭代遍歷新列表很多次,那麼實際上每次都會重新計算表達式樹*,在這種情況下,你可能想在末尾加上一個'.ToList()'來強制枚舉項目並創建一個新列表 – JaredReisinger 2010-08-06 23:24:43

19

您可以使用List<T>.GetRange()

var subList = myList.GetRange(0, 20); 

從MSDN:

創建範圍的元素的淺拷貝源List<T>

public List<T> GetRange(int index, int count)

2

SANS LINQ quicky ...

while (myList.Count>countIWant) 
     myList.RemoveAt(myList.Count-1); 
0
public static IEnumerable<TSource> MaxOf<TSource>(this IEnumerable<TSource> source, int maxItems) 
    { 
     var enumerator = source.GetEnumerator();    
     for (int count = 0; count <= maxItems && enumerator.MoveNext(); count++) 
     { 
      yield return enumerator.Current; 
     } 
    } 
+0

現在你可能會考慮添加一些解釋性文本,因爲經驗較少的用戶可能很難理解你的回答。 – Raad 2013-03-06 15:01:45

3

這可能是效率是有幫助,如果你真的想截斷名單,無法進行復印。雖然python示例創建了一個副本,但最初的問題確實是關於截斷列表。

給定一個列表<>目標「清單」,你想第1到第20個元件

list.RemoveRange(20, list.Count-20); 

這確實到位。這仍然是O(n),因爲必須刪除每個對象的引用,但應該比任何其他方法快一點。