C# 将项目添加到列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16853463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Add item to list
提问by 1321941
I have a list like so:
我有一个这样的清单:
List<string> songs = new List<string>();
and many objects in the form of:
以及以下形式的许多对象:
{'artist' => '....', 'title' => '.....', 'discnumber' => '...'}
Which are being created in a loop. What I am trying to do is add the object to the list.
哪些是在循环中创建的。我想要做的是将对象添加到列表中。
Thanks
谢谢
采纳答案by Tim Schmelter
I would suggest to create a custom class Songwith properties like Artist,Titleor Discnumber. Then use a List<Song>instead.
我建议创建一个自定义类Song,其属性如Artist,Title或Discnumber。然后使用 aList<Song>代替。
However, if you want to use your strings instead, i assume that you want to keep a csv-format:
但是,如果您想改用字符串,我假设您想保留 csv 格式:
foreach( <your Loop> )
{
songs.Add(String.Join(",", objects));
}
回答by petchirajan
If those are all the object of type string you can add like follows,
如果这些都是字符串类型的对象,您可以添加如下所示,
List<string> songs = new List<string>();
for(int i = 0; i < 10; i++)
{
songs.Add(i.ToString());
}
Or if you want Key,Value type, you can use dictionary,
或者如果你想要 Key,Value 类型,你可以使用字典,
Dictionary<string, String> Info = new List<string>();
Info.Add("Artist", "Some Artist");
Info.Add("Track", "Some Track");
//You can access the value as follows
string artist = info["Artist"]

