Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an enumeration of one

Tags:

c#

linq

c#-4.0

If I want an empty enumeration, I can call Enumerable.Empty<T>(). But what if I want to convert a scalar type to an enumeration?

Normally I'd write new List<string> {myString} to pass myString to a function that accepts IEnumerable<string>. Is there a more LINQ-y way?

like image 401
TrueWill Avatar asked Oct 27 '11 20:10

TrueWill


People also ask

How do you create an enumeration?

Enumeration is created by using a keyword called “enum”. Given below is the syntax with which we can create an enumeration. Note: enum can be defined only inside a top-level class or interface or in a static context. It should not be inside a method.

What is an example of enumeration?

Enumeration means counting or reciting numbers or a numbered list. A waiter's lengthy enumeration of all the available salad dressings might seem a little hostile if he begins with a deep sigh. When you're reciting a list of things, it's enumeration.

What is an enumeration number?

An enumeration is a data type that consists of a set of named values that represent integral constants, known as enumeration constants. An enumeration is also referred to as an enumerated type because you must list (enumerate) each of the values in creating a name for each of them.

What is enumeration in C++ with example?

Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration. The following is the syntax of enums. enum enum_name{const1, const2, ....... };


4 Answers

You can use Repeat:

var justOne = Enumerable.Repeat(value, 1);

Or just an array of course:

var singleElementArray = new[] { value };

The array version is mutable of course, whereas Enumerable.Repeat isn't.

like image 78
Jon Skeet Avatar answered Oct 06 '22 04:10

Jon Skeet


Perhaps the shortest form is

var sequence = new[] { value };
like image 29
Jon Avatar answered Oct 06 '22 04:10

Jon


There is, but it's less efficient than using a List or Array:

// an enumeration containing only the number 13.
var oneIntEnumeration = Enumerable.Repeat(13, 1);
like image 34
James Michael Hare Avatar answered Oct 06 '22 05:10

James Michael Hare


You can also write your own extension method:

public static class Extensions
{
    public static IEnumerable<T> AsEnumerable<T>(this T item)
    {
         yield return item;
    }
}

Now I haven't done that, and now that I know about Enumerable.Repeat, I probably never will (learn something new every day). But I have done this:

public static IEnumerable<T> MakeEnumerable<T>(params T[] items)
{
     return items;
}

And this, of course, works if you call it with a single argument. But maybe there's something like this in the framework already, that I haven't discovered yet.

like image 44
phoog Avatar answered Oct 06 '22 05:10

phoog