使用LINQ在赋值的左侧输出字符串变量

时间:2011-11-03 14:51:19

标签: linq

我正在使用LINQ查询Asp.NET MVC ModelStateDictionary,但我坚持以下查询:

public static DirectResult DirectValidation( this ModelStateDictionary state )
    {
        return new DirectResult()
        {
            Data = new
            {
                success = false,
                errors = from e in state
                        where e.Value.Errors.Count > 0
                        let errorName = e.Key
                        select new
                        {
                            errorName = e.Value.Errors.Select( x => x.ErrorMessage ).Concat( e.Value.Errors.Where( x => x.Exception != null ).Select( x => x.Exception.Message ) )
                        }

            }
        };

    }

特别是,我希望变量errorName出现在赋值的左侧。但是,目前看来,输出的是:

"errors": [
  {
    "errorName": [
      "Code must be unique"
    ]
  }
]

我如何编写LINQ以获得我想要的结果,例如

"errors": [
  {
    "Code": [
      "Code must be unique"
    ]
  }
]

1 个答案:

答案 0 :(得分:1)

问题在于左侧的东西是成员名称,而在静态类型语言中,成员名称是固定的。您可以尝试create a type dynamically,或者,如果您有权访问C#4,请使用ExpandoObject

object CreateExpando(string field, object o)
{
    var e = new ExpandoObject();
    var d = e as IDictionary<string, object>;
    d[field] = o;
    return e;
}

select CreateExpando(errorName, e.Value.Errors.Select...);