9

我有这个方法(简化):

void DoSomething(IEnumerable<int> numbers);

我这样调用它:

DoSomething(condition==true?results:new List<int>());

该变量results由 LINQ 选择条件 (IEnumerable) 构成。

我想知道这List<int>()是传递空集合的最佳方式(最快的方式?)还是new int[0]更好?或者,其他东西会更快, aCollection等?在我的例子null中是不行的。

4

2 回答 2

29

我会用Enumerable.Empty<int>()

DoSometing(condition ? results : Enumerable.Empty<int>());
于 2010-05-05T13:14:01.730 回答
1

@avance70。不是对原始问题的真正答案,而是对 avance70 关于仅具有 1 个整数值的 IEnumerable 问题的回应。会添加它作为评论,但我没有足够的代表来添加评论。如果您对严格不可变的序列感兴趣,您有几个选择:

通用扩展方法:

public static IEnumerable<T> ToEnumerable<T>(this T item)
{
  yield return item;
}

像这样使用:

foreach (int i in 10.ToEnumerable())
{
  Debug.WriteLine(i); //Will print "10" to output window
}

或这个:

int x = 10;
foreach (int i in x.ToEnumerable())
{
  Debug.WriteLine(i); //Will print value of i to output window
}

或这个:

int start = 0;
int end = 100;
IEnumerable<int> seq = GetRandomNumbersBetweenOneAndNinetyNineInclusive();

foreach (int i in start.ToEnumerable().Concat(seq).Concat(end.ToEnumerable()))
{
  //Do something with the random numbers, bookended by 0 and 100
}

我最近遇到了一个像上面的开始/结束示例这样的案例,我必须从序列中“提取”连续值(使用 Skip 和 Take),然后预先添加和附加开始和结束值。开始和结束值在最后一个未提取的值和第一个提取的值(开始)之间以及最后一个提取的值和第一个未提取的值(结束)之间进行插值。然后再次对产生的序列进行操作,可能会颠倒过来。

所以,如果原始序列看起来像:

1 2 3 4 5

我可能必须提取 3 和 4 并在 2 和 3 以及 4 和 5 之间添加插值:

2.5 3 4 4.5

可枚举。重复。像这样使用:

foreach (int i in Enumerable.Repeat(10,1)) //Repeat "10" 1 time.
{
  DoSomethingWithIt(i);
}

当然,由于这些是 IEnumerable,它们也可以与其他 IEnumerable 操作结合使用。不确定这些是否真的是“好”的想法,但他们应该完成工作。

于 2010-05-05T21:45:10.203 回答