Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Favorite way to create an new IEnumerable<T> sequence from a single value?

Tags:

c#

linq

c#-3.0

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.

like image 908
Marcel Lamothe Avatar asked Jun 19 '09 19:06

Marcel Lamothe


People also ask

What is IEnumerable t in c#?

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!

What is an IEnumerable?

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 better than list?

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.

What is the return type of IEnumerable in C#?

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).


1 Answers

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); 
like image 73
JaredPar Avatar answered Sep 23 '22 08:09

JaredPar