8

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

3
  • 4
    If you want to do it like that, why not just use a string? Commented Nov 28, 2011 at 15:38
  • I want to add many strings to the list and I want to display the list finally, How can I display the list. If I have more than 2 strings in the list Commented Nov 28, 2011 at 15:52
  • you can use the foreach to loop through the list and display them Commented Nov 28, 2011 at 15:58

4 Answers 4

22

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);
Sign up to request clarification or add additional context in comments.

Comments

10

Just as simple as that:

Resnames.Add(name);

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

Comments

1

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

Comments

0

Add String to List this way:

var ListName = new List<string>();

string StringName = "YourStringValue";

ListName.Add(StringName);

1 Comment

Is there anything new in comparison to the accepted and correct answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.