将值附加到现有IEnumerable的末尾时的yield return

时间:2012-04-11 11:47:31

标签: c# yield-return

我刚刚发现yield return,我觉得很好。我在这样的方法中使用它:

public IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
    if (Name == "Arbitary")
        yield return new ValidationResult("Bad Name.", new[] { "Name" });
    else if (Email == "BadEmail")
        yield return new ValidationResult("Bad Email.", new [] {"Email" });
    // further rules follow.
}

但是,我需要更改此方法以从子方法返回一些ValidationResults。如果不使用yield,代码将如下所示:

public override IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
    // TryValidateObject fills the ICollection you pass it.
    List<ValidationResult> retVal = new List<ValidationResult>();
    Validator.TryValidateObject(this, vc, retVal, true);

    if (Name == "Arbitary")
        retVal.Add(new ValidationResult("Bad Name.", new[] { "Name" }));
    else if (Email == "BadEmail")
        retVal.Add(new ValidationResult("Bad Email.", new[] { "Email" }));

    return retVal;
}

是否可以使用yield重写此内容?

3 个答案:

答案 0 :(得分:3)

你在找这个吗?

public override IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
    // TryValidateObject fills the ICollection you pass it.
    List<ValidationResult> retVal = new List<ValidationResult>();
    Validator.TryValidateObject(this, vc, retVal, true);
    foreach (var item in retVal)
        yield return item;
    if (Name == "Arbitary")
        yield return new ValidationResult("Bad Name.", new[] { "Name" });
    else if (Email == "BadEmail")
        yield return new ValidationResult("Bad Email.", new[] { "Email" });       
}

如果是这样,我相信第一个版本看起来更好。

答案 1 :(得分:3)

到目前为止发布的其他解决方案都很好。这是解决问题的另一种方法:

  • 创建两个序列
  • 连接它们
  • 返回连接。

所以:

public override IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
  return ResultsFromValidator(vc).Concat(AdditionalResults());
}
private IEnumerable<ValidationResult> ResultsFromValidator(ValidationContext vc)
{
  List<ValidationResult> retVal = new List<ValidationResult>();
  Validator.TryValidateObject(this, vc, retVal, true);
  return retVal;
}
private IEnumerable<ValidationResult> AdditionalResults()
{
  if (Name == "Arbitrary")
    yield return new ValidationResult("Bad Name.", new[] { "Name" });
  ...
}

答案 2 :(得分:2)

不确定。只需使用:

foreach (var item in retVal) {
    yield return item;
}

之后,您还可以继续收益率回报。因此,您可以在调用方法后返回retVal,然后在第一个样本中继续。像这样:

public override IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
    List<ValidationResult> retVal = new List<ValidationResult>();
    Validator.TryValidateObject(this, vc, retVal, true);
    foreach (var item in retVal) {
        yield return item;
    }

    if (Name == "Arbitary")
        yield return new ValidationResult("Bad Name.", new[] { "Name" });
    else if (Email == "BadEmail")
        yield return new ValidationResult("Bad Email.", new[] { "Email" });
    //...
}