linq表达式(和匿名类型)的结果出错

时间:2013-06-24 13:19:08

标签: c# linq type-conversion

我班上有一个linq查询。当我尝试返回一个或另一个结果时,编译器会抛出与“匿名类型”相关的转换类型错误,但我找不到它的解决方案。

这是我的代码:

public static string VerificaExame(string desc)
{
    var model = new ExameContext();
    var res = model.DbExame.Where(exame => exame.Descricao.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Codigo = exame.Codigo });
    if (res == null)
        res = model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Descricao = exame.Descricao });
    var ret = res.FirstOrDefault();
    return JsonConvert.SerializeObject(ret);
}

错误信息:

  

无效的匿名类型成员声明符。必须使用成员分配,简单名称或成员访问声明匿名类型成员。

此错误表示:

res = model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Descricao = exame.Descricao });

1 个答案:

答案 0 :(得分:1)

使用其他变量(不要使用res

var res = model.DbExame.Where(exame => exame.Descricao.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Codigo = exame.Codigo });
//^ Now res is of a specific type (ie: IEnumerable<Anonymous1>)
if (res == null)
    var res2 = model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Descricao = exame.Descricao });
    //^ you cant affect res2 to res because they are of different type

if (res == null) res永远不会为空,您可能希望if (!res.Any())查看res是否有项目。


这是你应该做的:

public static string VerificaExame(string desc)
{
    var model = new ExameContext();
    object res = (object)model.DbExame.Where(exame => exame.Descricao.Trim() == desc.Trim())
                                .Select(exame => new { Id = exame.Id, Codigo = exame.Codigo })
                                .FirstOrDefault()
        ??
        (object)model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim())
                        .Select(exame => new { Id = exame.Id, Descricao = exame.Descricao })
                        .FirstOrDefault();

    if (res != null)
        return JsonConvert.SerializeObject(res);
    return JsonConvert.SerializeObject("");//Or throw an exception
}