2011-08-03 113 views
1

可能重複:
How can I create a singleton IEnumerable?
Favorite way to create an new IEnumerable<T> sequence from a single value?我怎麼能枚舉一個項目

說我需要返回只包含一個元素一個IEnumerable。

我會返回一個列表中

return new List<Whatever> (myItem); 

或與此有關的數組。

但我在我的代碼把這個處處之前最好將創建一個Singleton方法

public IEnumerable<T> Singleton (T t) 
{ 
yield return t 
} 

,是不是有這已經這樣做的方法?

+0

爲什麼你覺得你需要枚舉一個單身人士? –

+0

爲什麼單身人士更可取?這似乎是很少需要的東西,而且應該是專門針對該流程設計的。 –

+0

相關:http://stackoverflow.com/questions/1019737/favorite-way-to-create-an-new-ienumerablet-sequence-from-a-single-value –

回答

4

.NET框架中最接近的方法是Enumerable.Repeat(myItem,1),但我只是使用new[]{myItem}

+0

這並不像單一方法那樣高效 – user380719

+4

事實上它有效率更高。 –

+0

@user你爲什麼認爲它不如單例方法那樣高效? – Abel

2
Enumerable.Repeat(t, 1); 

這似乎相當。不知道什麼更好。

1
/// <summary> 
/// Retrieves the item as the only item in an IEnumerable. 
/// </summary> 
/// <param name="this">The item.</param> 
/// <returns>An IEnumerable containing only the item.</returns> 
public static IEnumerable<TItem> AsEnumerable<TItem>(this TItem @this) 
{ 
    return new [] { @this }; 
} 
+1

少數幾個擴展方法之一,你可能不想在'null'上引發異常。 – Abel

相關問題