简体   繁体   English

如何在c#中将字符串添加到数组列表

[英]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 我该怎么做

Since you are using List (not a legacy fixed-size array) you able to use List.Add() method: 由于您使用的是List (不是传统的固定大小数组),因此您可以使用List.Add()方法:

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): 如果要在实例化列表实例后添加项,则可以使用对象初始化(因为C#3.0):

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

Also you might find useful List.AddRange() method as well 您也可以找到有用的List.AddRange()方法

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

var otherNames = new List<string>();
otherNames.AddRange(resourceNames);

Just as simple as that: 就像那样简单:

Resnames.Add(name);

BTW: VisualStudio is your friend! 顺便说一句:VisualStudio是你的朋友! By typing a . 通过键入. after Resnames it would have helped you. 在Resnames之后它会帮助你。

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

Add String to List this way: 以这种方式添加String to List:

var ListName = new List<string>();

string StringName = "YourStringValue";

ListName.Add(StringName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM