【问题标题】:IndexOf returns -1 in foreach object in listIndexOf 在列表中的 foreach 对象中返回 -1
【发布时间】:2020-07-12 12:57:08
【问题描述】:

当我运行代码时,它返回 -1,尽管对象(在我的理解中)必须存在,因为它是由 foreach 语句生成的。 有人有想法吗?

public partial class Class1
{
    private List<Master_Menu_Item> Config
    {
        get { return JsonConvert.DeserializeObject<List<Master_Menu_Item>>(Json_string.Config); } //if you need an example json, i can provide it
    }

    private void Reload_Master_stack()
    {
        if (Config != null)
        {
            foreach (Master_Menu_Item master_Menu_Item in Config)
            {
                int index = Config.IndexOf(master_Menu_Item);
                Debug.WriteLine(index);
            }
        }
    }
}

class Master_Menu_Item
   {
       public string Name { get; set; }
        public string Icon_path { get; set; }
       public List<Bottom_Menu_Item> Bottom_Menu_Items { get; set; }
   }

【问题讨论】:

标签: c# list indexing


【解决方案1】:

您可以使用以下代码:

 if (Config != null)
            {
                foreach (Master_Menu_Item master_Menu_Item in Config)
                {
                    int index = Config.FindIndex(a => a.Id == Master_Menu_Item.Id );
                }
            }

【讨论】:

  • 为此,我必须将“id”定义添加到我的 Master_Menu_Item 类中。这是唯一的方法还是我错过了什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多