c# - 如何在字典中查找类的实例?

标签 c# wpf class mvvm dictionary

如果我一直在正确地研究这个,我之前得到了一些帮助,一个用户说使用 Dictionary 来存储我的 Country地点

所以我创建了我的 Dictionary:

Dictionary<string, NewCountryClass> NTCD = new Dictionary<string, NewcountryClass>();

当用户单击按钮时,它将触发此类,我希望它在运行时在 Dictionary 中创建 newCountryClass 的实例。它将添加字符串,即 newCountryTitle.Country,然后是 Class

public void AddCountryCollection()
{

    newCountryClass = new NewCountryClass(newCountry,"");
    Collections.Add(newCountryClass);
    NTCD.Add(newCountryClass.Country, newCountryClass);
}

假设用户在运行时添加了创建这个DictionaryCountry,并且他们添加了4个 Countries,但现在想返回并在第二个 Country 中添加 Place 标签。

这是 newCountryClass:

private string _country;

public string Country
{
   get { return _country; }
   set
   {
      if (_country.Equals(value))
         return;

      _country= value;
      RaisePropertyChanged(() => Country);
   }
}

private ICollection<string> _places;
public ICollection<string> Places
{
   get
   {
      if (_places== null)
         _places= new ObservableCollection<string>();
      return _places;
   }
   set
   {
      if (value == _places)
         return;

      _places= value;
      RaisePropertyChanged(() => Places);
   }
}

如果他们创建了 4 个,并且他们想在他们创建的第二个Country 内的列表中添加一个 Place,我怎样才能找到它?

最佳答案

只需使用您存储的 key :

NTCD["GER"].Places.Add("New Place inside GER");

如果你只想知道第二个,要么拿List<NewCountryClass>并使用 for 按索引迭代或采取 OrderedDictionary .它在添加时将对象键、对象值作为参数,您可以通过 NTCD[3] 访问它。 .

OrderedDictionary Class

关于c# - 如何在字典中查找类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21336547/

相关文章:

c# - 将计算属性添加到 wcf 客户端以进行绑定(bind)

c# - 将文件中的十六进制添加到 List<byte>

c# - MVVM 中异步命令的自动化测试

WPF 覆盖 ContextMenu 样式 - DropShadowEffect 不起作用

Ruby - 类方法中问号的使用

Python:从导入类调用方法

c# - 无法使用 Json 序列化 Web API 中的响应

c# - 如何从 WinForms 中的文本框移除焦点?

.net - 将滚动条放在项目控件中包含的环绕面板上

c++ - 在派生类中添加虚拟说明符