c# - 检查 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的属性。
解决方案
我认为您可以为此使用 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;
}
}
推荐阅读
- python - 如何确定我的数据集是否平衡?
- maven - IntelliJ IDEA 中的结构化 Maven 配置文件
- r - UseMethod(“accuracy”)错误:没有适用于“accuracy”的适用方法应用于“c('double','numeric')”类的对象
- android - ListView 中的 RadioButton 波纹效果
- c# - 未发现 xUnit 测试
- c# - 如何从 Word 文档中复制富文本内容控件的内容并使用 Open XML SDK 删除控件本身
- javascript - 信用卡检查器 luhn 算法 javascript
- vba - 为多个 word 文档添加现有的页眉和页脚
- python - Azure Functions:多个开发人员在同一个 Azure Function APP 上构建 Functions
- python-3.x - 如何将我的代码转换为一行?