gpt4 book ai didi

c# - FluentValidation 和对象集合其属性应该是唯一的

转载 作者:行者123 更新时间:2023-12-05 02:18:38 30 4
gpt4 key购买 nike

我有课:

Sponsored { int Order };

我收集了它:

IEnumerable<Sponsored> sponsored; 

我想检查 Order 对于这个集合是否是唯一的。

我可以通过 FluentValidation 来完成吗?

我有:

SponsoredValidator : AbstractValidator<IEnumerable<Sponsored>>

SponsoredValidator : AbstractValidator<Sponsored>

@编辑:它应该通过 ValidationAttribute 与 WebAPI POST 方法连接

[Validator(typeof(SponsoredValidator))]

最佳答案

public class SponsoredCollectionValidator : AbstractValidator<IEnumerable<Sponsored>>
{
private class SponsoredComparer : IEqualityComparer<Sponsored>
{
public bool Equals(Sponsored x, Sponsored y) => x?.Order == y?.Order;
public int GetHashCode(Sponsored obj) => obj.Order;
}

public SponsoredCollectionValidator()
{
RuleFor(coll => coll)
.Must(coll => coll.Distinct(new SponsoredComparer()).Count() == coll.Count())
.WithMessage("Elements are not unique.");
}
}

关于c# - FluentValidation 和对象集合其属性应该是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44648980/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com