开发者

How can I enumerable one item [duplicate]

This question already has answers here: Closed 11 years ago. 开发者_如何学Python

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); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜