I usually create a sequence from a single value using array syntax, like this:
IEnumerable<string> sequence = new string[] { "abc" };
Or using a new List. I'd like to hear if anyone has a more expressive way to do the same thing.
Background Topics - IEnumerable<T> That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
Is IEnumerable faster than List? IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.
IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).
Your example is not an empty sequence, it's a sequence with one element. To create an empty sequence of strings you can do
var sequence = Enumerable.Empty<string>();
EDIT OP clarified they were looking to create a single value. In that case
var sequence = Enumerable.Repeat("abc",1);
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