以下是我循环执行的一段代码:

首先,在第一个查询中,我获得了位置ID列表。该列表可能很长。

最终,我需要找到哪个LocationId FamiliId > 0

我将其循环完成,但是我想在一个问题中完成。有可能吗?

var locationIds = context.TblUsersDistricts
 .Where(d => d.UserId == userId && d.ValidityTo == null)
 .Select(x => x.LocationId).ToList();

int familyId = 0;

foreach(var item in locationIds) {
   familyId = (from I in context.TblInsuree
   join F in imisContext.TblFamilies on I.FamilyId equals F.FamilyId
   join V in imisContext.TblVillages on F.LocationId equals V.VillageId
   join W in imisContext.TblWards on V.WardId equals W.WardId
   join D in imisContext.TblDistricts on W.DistrictId equals D.DistrictId
   where(I.Chfid == chfid &&
   D.DistrictId == item &&
   F.ValidityTo == null &&
   I.ValidityTo == null &&
   V.ValidityTo == null &&
   W.ValidityTo == null &&
   D.ValidityTo == null)
   select F.FamilyId)
  .FirstOrDefault();

 if (familyId > 0) break;
};

最佳答案

听起来像您想要的:

var familyId = (
    from item in locationIds
    from I in context.TblInsuree
    // ... etc
    && D.ValidityTo == null)
    select F.FamilyId)
    .FirstOrDefault();


关于c# - 缩短LINQ中的一个QUERY的循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57432705/

10-15 06:45