c# - 将项目添加到 List<string> 属性

标签 c# list class object add

如何将新项目添加到我的列表中?

这是我的对象列表或者其他人怎么调用它

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/

相关文章:

C#:I/O 繁重的多线程性能不佳

python - 修改原始列表直到找到一个字符串

python - 获取两个二维列表之间的差异

xcode - 如何访问另一个类中的变量?

class - Symfony2 验证约束 'Symfony\Component\Validator\Constraints\MaxLength' 未找到

c# - 将 Bootstrap 控件与 Razor HTML 帮助程序相结合

c# - INotifyPropertyChanged 和自动属性

c# - 如何在运行时更改列表框的数据模板方向?

c++ - 在 C++ 中使用 STL 通过邻接表表示图形

java - 在 Hibernate 中建模限定关系