3

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?

Community
  • 1
  • 1
user380719
  • 9,663
  • 15
  • 54
  • 89
  • 1
    Why do you feel you need to enumerate a singleton? – Eric J. Aug 03 '11 at 17:34
  • Why would the singleton be preferable? It seems like something rarely needed, and when it should be ad-hoc, tailored to the flow. – H H Aug 03 '11 at 17:34
  • Related: http://stackoverflow.com/questions/1019737/favorite-way-to-create-an-new-ienumerablet-sequence-from-a-single-value – Kevin Stricker Aug 03 '11 at 17:36
  • 3
    When you use the term "singleton", people are going to think of the singleton pattern. What you're doing here is not implementing the singleton pattern, it's emitting a sequence with a single item in it. – 48klocs Aug 03 '11 at 17:57

4 Answers4

7

The closest method available in the .NET framework is Enumerable.Repeat(myItem,1) but I would just use new[]{myItem}.

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
2
Enumerable.Repeat(t, 1);

That seems equivalent. Don't know anything better.

Ivan Danilov
  • 14,287
  • 6
  • 48
  • 66
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 };
}
Paul Ruane
  • 37,459
  • 12
  • 63
  • 82
  • 1
    One of the few extension methods use-cases where you may not want to throw an exception on `null`. – Abel Aug 03 '11 at 18:03
1

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); 
Community
  • 1
  • 1
Rahul
  • 76,197
  • 13
  • 71
  • 125