代码之家  ›  专栏  ›  技术社区  ›  Johan Leino

在对集合启动Linq查询之前对其进行“筛选”

  •  1
  • Johan Leino  · 技术社区  · 15 年前

    我正在处理一些验证代码,我的Linq代码有一些问题。

    我拥有的是一个对特定属性(ValidationAttribute)进行验证的类。所有这些都可以很好地工作,即验证工作在一个类中,该类具有一些用该属性(或其子类)修饰的属性。

    所以我的问题是,如何首先找到所有具有validation属性的属性(我已经为其编写了代码),但首先“过滤”该集合以忽略具有ignore属性的属性(或者实际上是列表集合)。

    验证的代码如下所示:

    from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                       from attribute in prop.Attributes.OfType<ValidationAttribute>().
                       where attribute.IsValid(prop.GetValue(instance)) == false
                       select new ...etc
    

    有什么想法吗?

    更新:

    我想我的问题是:

    class MyClass
    
    [Required]
    public string MyProp { get; set; }
    
    [Required]
    [Ignore]
    public string MyProp2 { get; set; }
    

    如何查找具有validation属性(required inherits that))但不具有ignore属性的所有属性?尽管我真的希望它忽略属性列表,而不仅仅是忽略属性。

    2 回复  |  直到 15 年前
        1
  •  2
  •   Amy B    15 年前

    不是吗?

    from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>() 
    where !prop.Attributes.OfType<IgnoreAttribute>().Any()
    from attribute in prop.Attributes.OfType<ValidationAttribute>(). 
    where attribute.IsValid(prop.GetValue(instance)) == false 
    select new ...etc 
    
        2
  •  1
  •   Marc Gravell    15 年前

    你需要这个吗 PropertyDescriptor

        var filtered = instance.GetType().GetProperties()
            .Where(prop => !Attribute.IsDefined(prop, typeof(IgnoreAttribute)));
    

    或者做整个事情:

        var invalid = from prop in instance.GetType().GetProperties()
                       where !Attribute.IsDefined(prop, typeof(IgnoreAttribute))
                       let valAttribs = Attribute.GetCustomAttributes(
                                prop, typeof(ValidationAttribute))
                       where valAttribs != null && valAttribs.Length > 0
                       let value = prop.GetValue(instance, null)
                       from ValidationAttribute valAttrib in valAttribs
                       where !valAttrib.IsValid(value)
                       select new {};
    
    推荐文章