我怎样才能枚举一个项目

时间:2011-08-03 17:31:53

标签: c# .net ienumerable

  

可能重复:
  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
}

在我将代码放在我的代码中之前,是不是已经有了这样做的方法呢?

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

Enumerable.Repeat(t, 1);

这似乎相当。别了解更多。

答案 2 :(得分: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 };
}

答案 3 :(得分:1)

取自Passing a single item as IEnumerable<T>

你可以像

一样传递一个项目
new T[] { item } 

或者在C#3.0中,您可以使用System.Linq.Enumerable

System.Linq.Enumerable.Repeat(item, 1); 
相关问题