2011-03-29 53 views
0

我正在重新調整函數中的月份列表。添加到列表中的c#

我期待着看看是否有一個優雅的解決方案,將3個元素添加到列表的開頭。

感謝您的建議。

+0

當你說列表中,你的意思System.Collections.ArrayList,System.Array的,月[],System.Collections.Generic.List , System.IEnumerable 還是別的?根據您返回的類型,解決方案可能會有很大差異。 – earlNameless 2011-03-29 01:35:04

回答

6

您可以使用List.Insert()的是,它需要在要添加新項目的指標,即在開始添加:

list.Insert(0, item); 

而且在同一時間加入多個項目您可以使用List.InsertRange()這需要一個IEnumerable作爲第二個參數:

list.InsertRange(0, itemCollection); 
+0

不要忘記list.InsertRange – Pete 2011-03-29 01:39:14

2
List<int> listOfMonths = new List<int>(); 
// ... insert months here 
listOfMonths.InsertRange(0, new int[] { 1, 2 ,3 }); 
0

讓我們發瘋......

// in a static class in a namespace you can see 
    public static IEnumerable<T> Prepend<T>(this IEnumerable<T> second, IEnumerable<T> first) 
    { 
     foreach (var x in first) 
     { 
      yield return x; 
     } 
     foreach (var x in second) 
     { 
      yield return x; 
     } 
    } 

    ... 

    var newListOfMonths = listOfMonths.Prepend(someExtraItems).ToList();