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

Check if ICollection contains an element based on a property

在 C-Sharp 中,我有一个 Registrations class,它基本上创建了一个包含 Questions 项的列表,如下所示:

public partial class Registrations
{
    public Registrations()
    {
        this.Questions = new HashSet<Questions>();
    }

    public int id { get; set; }
    public virtual ICollection<Questions> Questions { get; set; }
}

我的 Questions class 有一个名为 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; }
}

当用户创建注册时,他可以添加许多不同标题的问题。我想检查特定注册是否有标题为 "City" 的字段。我想在我的注册 class 中创建一个名为 hasCity 的函数,它将 return 一个 boolean 取决于特定注册是否有该字段。

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

现在,上面的函数总是 returns false 我猜这是因为我需要创建某种方法来只检查字符串的 Title 属性值城市.

我认为您可以为此使用 LinQ 中的 Any 方法。尝试以下操作。希望对朋友有帮助:

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;
        }
    }