问题
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)
回答1:
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.
回答2:
you could do this:
public IEnumerable<Foo> GetSingleFooAsEnumerable() {
yield return singleFoo;
}
回答3:
The best idiomatic way to do this is something like new[] { foo }
which just creates a 1-element array of whatever type foo
is declared to be.
The one possible downside to this is that arrays aren't immutable, so somebody can cast your IEnumerable<T>
to a T[]
and change the value in there. This is fairly unlikely, though, so I don't worry about it.
回答4:
IENumerable is supposed to be used for something that you can enumerate through, so using it for a single instance seems quite strange. If you really need to, you can get it done like this. It might be a better way, but this should get the job done:
List<foo> myList = new List<foo>();
myList.Add( myInstanceOfFoo );
IEnumerable myEnumerable = myList.AsEnumerable();
Regardless of how you see this, you are actually trying to make a list of one element, and then it's really no reason to make it a list.
来源:https://stackoverflow.com/questions/4779442/return-single-instance-object-as-ienumerable