【问题标题】:Take any single record if matching records not available - Linq如果匹配记录不可用,则获取任何单个记录 - Linq
【发布时间】:2018-11-23 06:58:10
【问题描述】:

我有多个记录的 linq 查询,我正在使用 where 子句过滤这些记录。

现在,如果过滤后的记录没有返回任何内容,那么我需要将其设为默认值,以从列表中获取默认的任何单个记录。

var resultStaffGua = (from s in _db.Students
 join sg in _db.StudentStaffGuardians on s.StudentID equals sg.StudentId
 join g in _db.Staffs on sg.StaffId equals g.StaffID
 join lr in _db.luRelationTypes on sg.RelationTypeId equals lr.RelationTypeID
 join ga in _db.StaffAddresses on g.StaffID equals ga.StaffID
 join ad in _db.Addresses on ga.AddressID equals ad.AddressID
 where
 lse.StatusID == (int?)Extension.StatusType.Active 
 && lse.TenantID == tenantid
 select new
 {
     g.FirstName,
     g.LastName,
     IsPrimary = sg.IsPrimaryGuardian,
     se.Email,
     Phone = sphon.PhoneNumber,
     lr.RelationCD,
     gdnr.GenderCD,
     ad.Zipcode
 }).Where(i=>i.IsPrimary==true);

如果resultStaffGua 计数0,我需要来自resultStaffGua 的一条记录。谢谢

【问题讨论】:

  • 什么result?什么parentList?除此之外我不明白这个问题
  • @MickyD - 查看我的更新问题。
  • @CGPA6.4,您尝试过 JohnWu 的以下回答吗?
  • @er-shoaib -John 的回答看起来直截了当。我本来可以想到的。我愿意做单行。谢谢。

标签: c# .net linq linq-to-entities


【解决方案1】:

假设您的意图是检索一条记录(IsPrimary==true 最多有一条记录):

var query = (from s in...); //The whole query except the "where"
var resultStaffGua = query.SingleOrDefault(i=>i.IsPrimary==true) ?? query.First();

否则,如果查询实际上可以返回多个结果:

var query = (from s in...);
var resultStaffGua = query.Where(i=>i.IsPrimary==true);
if(resultStaffGua.Count() == 0) resultStaffGua = new[] { query.First(); }

【讨论】:

  • 感谢您的解决方案。我不能在一行中做到这一点,所以我需要额外的query 变量。结果直接来自resultStaffGua
【解决方案2】:

如果结果计数为 0,我需要来自 parentList 的一条记录。

有时,显而易见的解决方案是最好的。为什么不在你的代码后面加上这个?

if (resultStaffGua.Count() == 0) 
{
    resultStaffGua = parentList.First();  
}

如果您想“聪明”并在一行中完成所有操作(我想这也可能会节省数据库事务),您可以将您的Where 换成OrderByTake

所以而不是:

).Where(i=>i.IsPrimary==true);

你可以这样做:

).OrderBy( i => i.IsPrimary ? 0 : 1 ).Take(1);

这将优先考虑将 IsPrimary 设置为 true 的任何记录,但无论是否匹配,它都会获得一条记录。

【讨论】:

  • 感谢您的回答。我本可以想到它,但我想要解决方案,而不是我可以在一行中完成它。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-11-26
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多