In the above example, List<int> primeNumbers = new List<int>(); creates a list of int type. In the same way, cities and bigCities are string type list. You can then add elements in a list using the Add() method or the collection-initializer syntax.
To add the contents of one list to another list which already exists, you can use: targetList. AddRange(sourceList); If you're just wanting to create a new copy of the list, see the top answer.
You can take advantage of the Enumerable.Range()
method:
var numberList = Enumerable.Range(1, 10).ToList();
The first parameter is the integer to start at and the second parameter is how many sequential integers to include.
If your initialization list is as simple as a consecutive sequence of values from from
to end
, you can just say
var numbers = Enumerable.Range(from, end - from + 1)
.ToList();
If your initialization list is something a little more intricate that can be defined by a mapping f
from int
to int
, you can say
var numbers = Enumerable.Range(from, end - from + 1)
.Select(n => f(n))
.ToList();
For example:
var primes = Enumerable.Range(1, 10)
.Select(n => Prime(n))
.ToList();
would generate the first ten primes assuming that Prime
is a Func<int, int>
that takes an int n
and returns the n
th prime.
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