簡體   English   中英

將空的IEnumerable參數傳遞給方法

[英]Passing an empty IEnumerable argument to a method

我有這個方法(簡化):

void DoSomething(IEnumerable<int> numbers);

我這樣調用它:

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

變量results由LINQ選擇條件(IEnumerable)形成。

我想知道這個List<int>()是傳遞空集合的最好方法(最快嗎?),還是new int[0]更好? 或者,其他東西會更快, Collection等等? 在我的例子中, null不行。

我使用Enumerable.Empty<int>()

DoSometing(condition ? results : Enumerable.Empty<int>());

@ 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

Enumerable.Repeat。 使用這樣:

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

當然,由於這些是IEnumerables,它們也可以與其他IEnumerable操作一起使用。 不確定這些是否真的是“好”的想法,但他們應該完成工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM