按枚举列出不同枚举的列表

时间:2016-06-30 12:35:28

标签: c# linq generics

我有这个类接受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)时,上面的构造函数工作正常。

现在我需要扩展上面的内容,以便传递的错误可能包含不同的枚举类型(例如CustomerErrorCustomerBankAccountError等),所以我要添加一个新属性:

public IReadOnlyDictionary<Type, IReadOnlyDictionary<object, string>> ExtraErrors { get; private set; }

使用Linq,如何:

  1. 过滤掉并将T类型的枚举值放入&#34;错误&#34;字典?
  2. 过滤掉剩余的枚举值并将其分组到&#34; ExtraErrors&#34;
  3. 中的单独词典中

1 个答案:

答案 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));
}