在同一语句中使用linq和返回类型查询项
本文关键字:linq 返回类型 查询 语句 | 更新日期: 2023-09-27 18:15:46
我有以下两行代码,首先从查询返回一个项目,然后用第一个查询的值创建另一个项目。我想把这两行合并成一句话。请记住,在某些情况下,第一个查询的结果可能为空。
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(我假设Profiles是一个)
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)
);