繁体   English   中英

使用linq查询项目并在同一条语句中返回类型?

[英]query item using linq and return type in the same statement?

我有以下两行代码,它们首先从查询中返回一个项目,然后使用第一个查询的值创建另一个项目。 我想将这两行结合成一条语句。 请记住,在某些情况下,第一个查询的结果可能为null。

var x = uow.Profiles.FindByID(profileId).Competitor;

return Json(new Organisation() { Name = x.Name, ID = x.ID, IsClient = x.IsClient, IsDeleted = x.IsDeleted }, JsonRequestBehavior.AllowGet);

如果这是您关心的问题,也许可以添加一个空检查:

var result = uow.Profiles.FindByID(profileId);

if(result != null)
{
   var competitor = result.Competitor;
   return Json(new Organisation() { Name = competitor.Name, ID = competitor.ID, IsClient = competitor.IsClient, IsDeleted = competitor.IsDeleted }, JsonRequestBehavior.AllowGet);
}

return null; // or whatever you can default to

不知道到底是什么问题和LINQ如何帮助(你没有必要必须使用它),只要确保你的代码是可读的。

编辑:最后使用IEnumerable(我假设配置文件是一个)

ouw.Profiles.Single(p => p.Id == profileId).Select
(p => Json(
    new Organisation()
    {
        Name = p.Competitor.Name,
        ID = p.Competitor.ID,
        IsClient = p.Competitor.IsClient,
        IsDeleted = p.Competitor.IsDeleted
    },
    JsonRequestBehavior.AllowGet)
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM