Eft*_*ari 4 c# class list add object
我怎样才能在列表中添加新项目?
这是我的对象列表或任何人称之为
class WordListsAll
{
public int idAll { get; set; }
public string wordEnAll { get; set; }
public string translationAll { get; set; }
public List<string> videosOfSelectedWord { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想要的是向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)
});
}
Run Code Online (Sandbox Code Playgroud)
有时我想回来并为之前创建的实例添加一个新的myCustomString.Imagin有一个单词"hello",视频名称为"Dexter",并且还有一个单词"hello",但这次的视频名称为"Breaking Bad".
如何将这些视频名称添加到我的视频属性列表中?OfSelectedWord?
您必须自己分配列表 - 您可以使用集合初始值设定项执行此操作:
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 }
});
}
Run Code Online (Sandbox Code Playgroud)
要添加到现有项目,可能是这样的(从你的问题不完全清楚,你可能应该做一些阅读):
//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
}
Run Code Online (Sandbox Code Playgroud)
(顺便说一句,你的名字应该遵循命名约定,所以属性应该大写)