代码之家  ›  专栏  ›  技术社区  ›  Tales

检查ICollection是否包含基于属性[duplicate]的元素

  •  0
  • Tales  · 技术社区  · 6 年前

    在C-夏普我有一个 Registrations Questions 像这样的项目:

    public partial class Registrations
    {
        public Registrations()
        {
            this.Questions = new HashSet<Questions>();
        }
    
        public int id { get; set; }
        public virtual ICollection<Questions> Questions { get; set; }
    }
    

    我的 问题 Title 它只是给出表单字段标签。

    public partial class Questions
    {
        public int id { get; set; }
        public int registrationId { get; set; }
        public string Title { get; set; }
        public string Data { get; set; }
    }
    

    当用户创建注册时,他可以添加许多具有不同标题的问题。我想检查特定的注册是否有标题字段 “城市” . 我想在注册类中创建一个名为 hasCity boolean

    public hasCity()
    {
        Questions city = new Questions();
        city.Title = "City";
        if( this.Questions.Contains( city ) )
        {
            return true;
        }
        return false;
    }
    

    false 我猜这是因为我需要创建某种方法来检查 职务 城市 .

    1 回复  |  直到 6 年前
        1
  •  0
  •   Tomato32    6 年前

    我想你可以用LinQ中的任何方法来实现这个。请尝试以下操作。希望能帮上忙,我的朋友:

    public partial class Questions
        {
            public int id { get; set; }
            public int registrationId { get; set; }
            public string Title { get; set; }
            public string Data { get; set; }
        }
    
        public partial class Registrations
        {
            public Registrations()
            {
                this.Questions = new HashSet<Questions>();
            }
    
            public int id { get; set; }
            public virtual ICollection<Questions> Questions { get; set; }
            public bool HasCity(string titleCity)
            {            
                if (this.Questions.Any(x => x.Title.ToLower() == titleCity.ToLower()))
                {
                    return true;
                }
                return false;
            }
        }
    
    推荐文章