我有这个类接受FluentValidation错误列表并将它们放在字典中。
public class ErrorList<T> : ISerializable where T : struct, IConvertible
{
public IReadOnlyDictionary<T, string> Errors { get; private set; }
public ErrorList(IList<ValidationFailure> errors)
{
Errors = (from e in errors
select new
{
e.PropertyName,
e.CustomState
}).ToDictionary(t => (T)t.CustomState, t => t.PropertyName);
}
}
当列表包含一个特定枚举类型的值(例如CustomerError
)时,上面的构造函数工作正常。
现在我需要扩展上面的内容,以便传递的错误可能包含不同的枚举类型(例如CustomerError
,CustomerBankAccountError
等),所以我要添加一个新属性:
public IReadOnlyDictionary<Type, IReadOnlyDictionary<object, string>> ExtraErrors { get; private set; }
使用Linq
,如何:
T
类型的枚举值放入&#34;错误&#34;字典?答案 0 :(得分:0)
如果您想使用LINQ,只需使用where
将元素过滤为两个集合:
public ErrorList(IEnumerable<ValidationFailure> errors)
{
// e.CustomState is of type T ?
Errors = errors
.Where(e => (e.CustomState is T))
.ToDictionary(e => (T)e.CustomState, e => e.PropertyName);
// e.CustomState is not of type T ?
ExtraErrors = errors
.Where(e => !(e.CustomState is T))
.GroupBy(e => e.CustomState.GetType())
.ToDictionary(
g => g.Key,
g => (IReadOnlyDictionary<object, string>)g.ToDictionary(
e => e.CustomState,
e => e.PropertyName));
}