Murthy
Murthy

Reputation: 1552

How to add string to an array list in 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

Upvotes: 8

Views: 83405

Answers (4)

Bamidelzz
Bamidelzz

Reputation: 106

Add String to List this way:

var ListName = new List<string>();

string StringName = "YourStringValue";

ListName.Add(StringName);

Upvotes: 0

sll
sll

Reputation: 62484

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);

Upvotes: 22

Ali Hasan
Ali Hasan

Reputation: 1075

try adding the string to array list like this,

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


foreach (var item in Resnames)
{
    Console.WriteLine(item);
}

Upvotes: 1

Fischermaen
Fischermaen

Reputation: 12458

Just as simple as that:

Resnames.Add(name);

BTW: VisualStudio is your friend! By typing a . after Resnames it would have helped you.

Upvotes: 10

Related Questions