2016-07-26 49 views
1

我有一個列表列表。 爲了對這些列表中的每一個做一些操作,我用一個屬性分開列表,並用它的值設置一個臨時列表; 該列表有時可能爲空。 這就是爲什麼我使用此功能進行分配。編輯: 我目前的解決方案是這種簡單的方法。 它應該很容易適應。c#用另一個列表/新列表初始化一個列表

private List<string> setList(List<string> a, int count) 
    { 
     List <string> retr; 
     if(a.Capacity == 0) 
     { 
      retr = new List<string>(); 
      for(int counter = 0; counter < count; counter++) 
      { 
       retr.Add(string.empty); 
      } 
     } 
     else 
     { 
      retr = a; 
     } 
     return retr; 
    } 

有沒有更好的方法來獲取列表作爲值或初始化一個列表元素數? 或者我應該實現自己的「List」類有這種行爲?

+4

'List.Capacity'與'List.Count'不同,它在清除列表時不會被修剪。這種方法有什麼意義?如果前一個也是空的,爲什麼不實例化一個新列表?另外,代碼中沒有「列表清單」。 – Groo

+0

我知道容量與count不同。在初始化中,我不在乎子列表中有多少元素,但有多少元素可以存在。 – gismo

+0

可能沒有客觀上更好的方法來做這個非常不直觀的事情,除了首先不需要做這件事。即使如此,「有沒有更好的方法」,對於工作代碼來說,這種問題對於代碼評審來說更爲重要。 –

回答

2

你可以使用Enumerable.Repeat<T>如果你想避免循環:

var list = Enumerable.Repeat<string>("", count).ToList(); 

但也有幾件事情是有問題與您的代碼:

  1. 如果Capacity不是0,它不這並不意味着它等於你想要的count。即使它等於指定的count,但這並不意味着實際List.Count等於count。一個更安全的方法是做:

    static List<string> PreallocateList(List<string> a, int count) 
    { 
        // reuse the existing list? 
        if (a.Count >= count) 
         return a; 
    
        return Enumerable.Repeat("", count).ToList(); 
    } 
    
  2. 預分配一個List<T>是不尋常的。事先已知固定長度時,通常使用數組。

    // this would (perhaps) make more sense 
    var array = new string[count]; 
    
  3. 而且記住,在1提到,該名單的Capacity是不一樣的Count

    var list = new List<string>(10); 
    
    // this will print 10 
    Console.WriteLine("Capacity is {0}", list.Capacity); 
    
    // but this will throw an exception   
    list[0] = ""; 
    

最有可能的,但是,這種方法是不必要的,有是一種更好的方式來完成你正在做的事情。如果不出意外,我會打安全牌,只是每次都實例化一個新的列表(假定你有依賴預分配列表上的算法):

static List<string> PreallocateList(int count) 
{ 
    return Enumerable.Repeat("", count).ToList(); 
} 

或者,如果你只對具有感興趣右容量(不計),那麼就使用適當的構造函數:

static List<string> PreallocateList(int count) 
{ 
    // this will prevent internal array resizing, if that's your concern 
    return new List<string>(count); 
} 
+0

謝謝,我知道數組更適合這份工作。我試圖弄亂C#及其內置的數據模型。 – gismo

0

你的方法是沒有意義的,但等同於

static List<string> setList(List<string> a, int count) => 
    a.Capacity == 0 ? Enumerable.Repeat("", count).ToList() : a; 

如果你想Linq。