如何将新项目添加到我的列表中?
这是我的对象列表或者其他人怎么调用它
class WordListsAll
{
public int idAll { get; set; }
public string wordEnAll { get; set; }
public string translationAll { get; set; }
public List<string> videosOfSelectedWord { get; set; }
}
我只想在 videosOfSelectedWord 列表属性中添加一个新项目。
这样做的最佳方法是什么?
foreach (var item in q)
{
count++;
oWordListsAll.Add(new WordListsAll
{
idAll = count,
wordEnAll = item.Element("Word").Value,
translationAll = item.Element("Translation").Value,
///////////////here is my goal///////////////////
videosOfSelectedWord.Add(myCustomString)
});
}
有时我想回来为之前创建的实例添加一个新的myCustomString。想象一下,视频名称“Dexter”出现了一个词“hello”,然后又出现了一个词“hello”,但这次视频名称是“Breaking Bad”。
如何将这些视频名称添加到我的 videosOfSelectedWord 属性列表中?
最佳答案
您必须自己分配列表 - 您可以使用 collection initializer 来做到这一点:
foreach (var item in q)
{
count++;
oWordListsAll.Add(new WordListsAll
{
idAll = count,
wordEnAll = item.Element("Word").Value,
translationAll = item.Element("Translation").Value,
videosOfSelectedWord = new List<string> { myCustomString }
});
}
要添加到现有项目,可能是这样的(您的问题不完全清楚,您可能应该做一些阅读):
//should really use a dictionary, this is just to show a simple example
var alreadyExists = videosOfSelectedWord.FirstOrDefault(x => x.wordEnAll == item);
if(alreadyExists !=null)
{
alreadyExists.videosOfSelectedWord.Add(myCustomString);
alreadyExists.idAll++;
}
else
{
//new item
}
(顺便说一句,您的名字确实应该遵循命名约定,因此属性应该大写)
关于c# - 将项目添加到 List<string> 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25351262/