Question

Currently, I am declaring and initializing a list like this:

List<ushort> myList = new List<ushort>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

I will eventually have more ushort lists that will contain a lot more than 10 values and it's inefficient to type out every number between 1-100, for example. The list will always be a range of numbers.

Is there a shorter way to write this? I have tried researching Enumerable.Range, but that only handles int values and I receive a "Cannot implicitly convert type int to ushort" error.

Était-ce utile?

La solution

How about an explicit cast?

List<ushort> myList = Enumerable.Range(1, 100).Select(i => (ushort)i).ToList();

and then make it really short!

var myList = Enumerable.Range(1, 100).Select(i => (ushort)i).ToList();

Autres conseils

You could try using a loop to fill your list.

List<ushort> myList = new List<ushort>();

And then have this in a method:

ushort count = 100; //or whatever number you need

for (ushort i = 1; i < count + 1; i++)
    myList.Add(i);

One advantage to a loops, imo, is that if you in the future have a list of something, like classes, you can easily create different instances of the classes in the loop and add them to the list.

List<ushort> values= Enumerable.Range(1, 100).Select(x => (ushort) x).ToList();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top