Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add string to an array list in c#

Tags:

c#

I have a list and a string

var Resnames= new List<string>();
string name = "something";

I want to append string to it like

   Resnames  += name;

How can I do it

like image 927
Murthy Avatar asked Nov 28 '11 15:11

Murthy


People also ask

How do you append a string to the end of an array in C?

You can't append to an array. When you define the array variable, C asks the is for enough contiguous memory. That's all the memory you ever get. You can modify the elements of the array (A[10]=5) but not the size.

Can you add an array to a List C#?

Use the Add() method or object initializer syntax to add elements in an ArrayList . An ArrayList can contain multiple null and duplicate values. Use the AddRange(ICollection c) method to add an entire Array, HashTable, SortedList, ArrayList , BitArray , Queue, and Stack in the ArrayList .

What is the difference between List and ArrayList in C#?

ArrayLists vs Lists in C# The List class must always be preferred over the ArrayList class because of the casting overhead in the ArrayList class. The List class can save us from run-time errors faced due to the different data types of the ArrayList class elements.


1 Answers

Since you are using List (not a legacy fixed-size array) you able to use List.Add() method:

resourceNames.Add(name);

If you want to add an item after the instantiation of a list instance you can use object initialization (since C# 3.0):

var resourceNames = new List<string> { "something", "onemore" };

Also you might find useful List.AddRange() method as well

var resourceNames = new List<string>();
resourceNames.Add("Res1");
resourceNames.Add("Res2");

var otherNames = new List<string>();
otherNames.AddRange(resourceNames);
like image 54
sll Avatar answered Sep 30 '22 00:09

sll