我有一份清单。 要对每个列表执行一些操作,我将列表与属性分开,并设置临时列表及其值; 该列表有时可能为空。 这就是我使用这个功能进行分配的原因。
编辑: 我目前的解决方案是这种简单方法。 它应该很容易适应。
public class MatchItem : IEquatable<MatchItem>
{
public int SomeInt { get; set; }
public decimal SomeDecimal {get; set; }
public bool Equals(MatchItem item)
{
if(item == null)
return false;
return this.SomeInt == item.SomeInt && this.SomeDecimal == item.SomeDecimal;
}
// You should also override object.ToString, object.Equals & object.GetHashCode.
// Omitted for brevity here!
}
有没有更好的方法可以将列表作为值或使用元素计数初始化列表? 或者我应该实现我自己的具有此行为的“List”类?
答案 0 :(得分:2)
如果您想避免循环,可以使用Enumerable.Repeat<T>
:
var list = Enumerable.Repeat<string>("", count).ToList();
但是您的代码有几个问题:
如果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();
}
预先分配List<T>
是不寻常的。当您事先知道固定长度时,通常会使用数组。
// this would (perhaps) make more sense
var array = new string[count];
请注意,如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);
}
答案 1 :(得分:0)
你的方法毫无意义,但相当于
static List<string> setList(List<string> a, int count) =>
a.Capacity == 0 ? Enumerable.Repeat("", count).ToList() : a;
如果你想要Linq。