How can I enumerable one item [duplicate]
Possible Duplicates:
How can I create a singleton IEnumerable? Favorite way to create an new IEnumerable<T> sequence from a single value?
Say I need to return an IEnumerable which contains only one element.
I could return a list as in
return new List<Whatever> (myItem);
or an array for that matter.
But it would be preferable to create a Singleton method
public IEnumerable<T> Singleton (T t)
{
yield return t
}
Before I put this everywhere in my code, isn't there a method which already does this?
The closest method available in the .NET framework is Enumerable.Repeat(myItem,1)
but I would just use new[]{myItem}
.
Enumerable.Repeat(t, 1);
That seems equivalent. Don't know anything better.
/// <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 };
}
Taken from Passing a single item as IEnumerable<T>
You can wither pass a single item like
new T[] { item }
OR in C# 3.0 you can utilize the System.Linq.Enumerable
class
System.Linq.Enumerable.Repeat(item, 1);
精彩评论