How to return IEnumerable<T> for a single item
-
13-12-2019 - |
Question
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
Solution
IEnumerable<T> getItems()
{
if ( someCondition.Which.Yields.One.Item )
{
yield return MyRC;
}
else
{
foreach(var i in myList)
yield return i;
}
}
OTHER TIPS
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. Simply return this:
yield return new[] { singleItem };
or if it's an IEnumerable<List<T>>
then
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. The yield
keyword exists for a reason.
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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow