2016-07-26 48 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。