Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return single instance object as IEnumerable

I have in instance of class foo and i want to return it as IEnumerable. Can i do it without creating a new list etc..

Perhaps something like the following:

IEnumerable<foo>.fromInstance(foo)
like image 340
Adibe7 Avatar asked Jan 24 '11 06:01

Adibe7


1 Answers

Options:

  • Create an instance of a collection class, like an array or a list. This would be mutable by default, which would be slightly unhelpful if this is a sequence you want to be able to hand out in your API. You could create a ReadOnlyCollection<T> wrapper around such a collection though.
  • Write your own iterator block as per Botz3000's answer
  • Use Enumerable.Repeat(item, 1) from LINQ, if you're using .NET 3.5.

The best answer here depends on the usage. If you only need this to call another method which uses a sequence, and you know it won't be modified, I'd probably use an array. For example, in order to call Concat on some other sequence, you might want:

var wholeList = regularList.Concat(new[] { finalValue });

I have confidence that Concat isn't going to mutate the array, and nothing else will ever see the reference to the array itself.

If you need to return the sequence to some other code, and you don't know what it might do with it, I'd probably use Enumerable.Repeat.

like image 70
Jon Skeet Avatar answered Sep 19 '22 14:09

Jon Skeet