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)
Options:
ReadOnlyCollection<T>
wrapper around such a collection though.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With