2010-08-13 79 views
1

我正在處理一些驗證代碼,並且在我的Linq代碼中遇到了一些問題。在開始Linq查詢之前「過濾」一個集合

我所擁有的是一個在特定屬性(ValidationAttribute)上驗證的類。這一切都正常工作,即驗證與一個具有用該屬性(或其子類)裝飾的某些屬性的類一起工作。

我現在想要完成的是告訴我的「驗證器」類忽略所有用某個其他屬性標記的屬性(讓我們稱之爲IgnoreAttribute)。

所以我的問題是,我如何首先找到具有驗證屬性(我已經有代碼)的所有屬性,但首先「過濾」該集合忽略具有忽略屬性(或實際上是List採集)。

用於驗證的代碼如下所示:

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 

我想這個代碼忽略包含在一個列表,我在類的所有屬性,即某種過濾的原始集...

任何想法?

UPDATE:

我想我的問題真的是這樣的: 如果我有一個具有其屬性飾有類似屬性的類:

class MyClass 

[Required] 
public string MyProp { get; set; } 

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

如何找到所有的性質有驗證屬性(必須繼承)),但不是忽略屬性?雖然我真的不想忽略屬性列表,而不是忽略忽略屬性。

回答

1

沒有什麼?

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 
+0

是的,那工作...我爲什麼沒有想到那個......衝突者?謝謝你,對於遲到的回答感到抱歉! – 2010-08-17 10:55:32

1

你需要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 {}; 
+0

我真正想要的是有一個集合(所有的驗證屬性),但如果該屬性還飾有屬性的另一個列表屬性之一是應該忽視...更清楚?? 它真的與屬性只是Linq過濾無關 – 2010-08-13 07:54:29

+0

@Johan - 完全; IsDefined將這些屬性提前取走。更新是否更清晰? – 2010-08-13 07:55:39