首页 > 解决方案 > 检查 ICollection 是否包含基于属性的元素

问题描述

在 C-Sharp 我有一个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; }
}

我的Questions班级有一个名为的字段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"的字段。我想在我的 Registrations 类中创建一个名为的函数,该函数hasCity将返回一个boolean取决于特定注册是否具有该字段的函数。

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

现在,上面的函数总是返回false,我猜这是因为我需要创建某种方法来仅检查Title字符串值City的属性。

标签: c#icollection

解决方案


我认为您可以为此使用 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;
        }
    }

推荐阅读