2012-01-11 49 views
1

有沒有辦法擺脫.FirstOrDefault()以下設置。我喜歡使用yield單詞,但是我想將IsRequired方法濃縮到我不必使用.FirstOrDefault()的地步。替代方式編寫收益率

PlayerValidator

protected override IEnumerable<ValidationResult> Validate(PlayerModel entity, IValidationProvider validationProvider) 
     { 
      yield return ValidationResultHelper.IsRequired(entity.Profile.FirstName, "First Name").FirstOrDefault(); 

      if (string.IsNullOrWhiteSpace(entity.Profile.LastName)) 
       yield return new Required("Last Name"); 
     } 

ValidatorHelper

public IEnumerable<ValidationResult> IsRequired(string text, string name) 
{ 
    if (string.IsNullOrWhiteSpace(text)) 
     yield return new Required(name); 
} 
+2

如果'FirstName'有效,您的代碼是否意味着返回'null'? – 2012-01-11 01:43:56

+0

沒有,就像LastName返回一樣。 – 2012-01-11 01:45:57

+0

嗯,我不是'yield return' virtuoso,但是FirstOrDefault'的OrDefault'部分如果FirstName不是'null'或空白,會給你一個'null'值嗎? – 2012-01-11 01:54:33

回答

2

foreach會是另一種選擇(它不會在錯誤的情況下返回null沒有驗證錯誤在你的例子):

protected override IEnumerable<ValidationResult> Validate(PlayerModel entity, IValidationProvider validationProvider) 
{ 
    foreach (var result in ValidationResultHelper.IsRequired(entity.Profile.FirstName, "First Name")) 
     yield return result; 
    if (string.IsNullOrWhiteSpace(entity.Profile.LastName)) 
     yield return new Required("Last Name"); 
} 
1

我不是因爲我可能會熟悉yield return,但在這種情況下,我認爲您在IsRequired中使用yield return的方式正在使用錯誤的工具。我會稍有不同結構是:

ValidatorHelper

// Note this function is almost unnecessary and might be better 
// implemented in AddIfRequired if validation is this trivial. 
public static bool IsRequired(string text) 
{ 
    return string.IsNullOrWhiteSpace(text); 
} 

PlayerValidator

private static void AddIfRequired(string text, string name, List<ValidationResult> validationResults) 
{ 
    if (ValidatorHelper.IsRequired(text)) 
     requiredList.Add(new Required(name)); 
} 

protected override IEnumerable<ValidationResult> Validate(PlayerModel entity, IValidationProvider validationProvider) 
{ 
    List<ValidationResult> validationResults = new List<ValidationResult>(); 

    AddIfRequired(entity.Profile.FirstName, "First Name", validationResults); 
    AddIfRequired(entity.Profile.LastName, "Last Name", validationResults); 
    // ... 

    return validationResults; 
} 

如果你真的想用yield return並保存自己創建列表,每次驗證所有字段(雖然我不不認爲這將是一個性能問題),你可以將AddIfRequired分成ValidationResultIfRequiredValidate分別爲:

ValidationResult validationResult; 

// ... 

validationResult = ValidationResultIfRequired(entity.Profile.FirstName, "First Name"); 
if (validationResult != null) 
    yield return validationResult; 

validationResult = ValidationResultIfRequired(entity.Profile.LastName, "Last Name"); 
// etc