kartal
kartal

Reputation: 18086

select multiple elements in array and convert them to list c#

I have an array for example :

public static string[] elmentnames = { "A", "B", "C", "D", "E","F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R","S", "T", "U", "V", "W", "X", "Y", "Z"};

and I want to select items from index 0 to 15 and put then in a list of string

How?

Upvotes: 3

Views: 6014

Answers (3)

Chris Fulstow
Chris Fulstow

Reputation: 41872

Any of these will work:

var list = elmentnames.Take(16).ToList();
var list = elmentnames.Where((x, i) => i <= 15).ToList();

var array = new string[16];
Array.Copy(elmentnames, array, 16);
var list = new List<string>(array);

Upvotes: 3

Michael Low
Michael Low

Reputation: 24506

Presuming the elements are already in the order you want them, you can do it like:

List<string> elementNamesList = elmentnames.Take(15).ToList();

.Take(15) is the first 15 elements. From index 0 to 15 is actually 16 elements, so you can change that to .Take(16) if that's what you meant.

Upvotes: 6

Nistor Alexandru
Nistor Alexandru

Reputation: 5393

You should try creating a for loop that goes threw every element of your current array and ads them to an ArrayList I am not familiar with C# but the concept its the same in every programming language.

Upvotes: 1

Related Questions