[英]How to return IEnumerable<T> for a single item
I have a function which can return a list of items or a single item like so below ( pseudocode ) 我有一个函数可以返回项目列表或单个项目,如下所示(伪代码)
IEnumerable<T> getItems()
{
if ( someCondition.Which.Yields.One.Item )
{
List<T> rc = new List<T>();
rc.Add(MyRC);
foreach(var i in rc)
yield return rc;
}
else
{
foreach(var i in myList)
yield return i;
}
}
The 1st part seems a little kludgy, looking to make it readable 第一部分似乎有些笨拙,希望能让它变得可读
IEnumerable<T> getItems()
{
if ( someCondition.Which.Yields.One.Item )
{
yield return MyRC;
}
else
{
foreach(var i in myList)
yield return i;
}
}
You don't need to do anything: 你不需要做任何事情:
yield return MyRC;
you normally return the items one by one, not grouped in a collection. 您通常会逐个返回项目,而不是分组。
But if it's an IEnumerable<IList<T>>
then it's different. 但如果它是一个IEnumerable<IList<T>>
那么它就不同了。 Simply return this: 简单地回复一下:
yield return new[] { singleItem };
or if it's an IEnumerable<List<T>>
then 或者如果它是IEnumerable<List<T>>
那么
yield return new List<T> { singleItem };
It's not clear that you need to use an iterator block in the first place. 目前尚不清楚您是否需要首先使用迭代器块。 Do you need/want to defer execution? 你需要/想要推迟执行吗? Do you need/want to evaluate the condition multiple times if the caller iterates over the returned sequence multiple times? 如果调用者多次迭代返回的序列,您是否需要/想要多次评估条件? If not, just use: 如果没有,只需使用:
IEnumerable<T> GetItems()
{
if (someCondition.Which.Yields.One.Item)
{
return Enumerable.Repeat(MyRC, 1);
}
else
{
// You *could* just return myList, but
// that would allow callers to mess with it.
return myList.Select(x => x);
}
}
The List<T>
is unnecessary. List<T>
是不必要的。 The yield
keyword exists for a reason. yield
关键字存在是有原因的。
IEnumerable<T> getItems(){
if ( someCondition.Which.Yields.One.Item )
{
yield return MyRC;
}
else
{
foreach(var i in myList)
yield return i;
}
}
What about: 关于什么:
IEnumerable<T> getItems(){
if ( someCondition.Which.Yields.One.Item )
{
yield return MyRC;
}
else
{
foreach(var i in myList)
yield return i;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.