2014-02-10 90 views
2

我想選擇第二條LINQ輸出中不存在FeeZoneID的所有記錄。獲取第二條LINQ中不存在的所有記錄

我知道它可以很容易地使用NOT IN(....)在SQL中完成,但我在LINQ中做到了嗎?

from d in FeeZones 
where d.FeeZoneID !(from b in FeeZoneSchemes 
    where b.FeeSchemeID == 1 
    join c in FeeZones on b.FeeZoneID equals c.FeeZoneID 
    select c) 
select d 

在我的C#類,這是我過得怎麼樣:

public IList<FeeZone> _LQ_GetAllAvaliableFeeZoneForGivenFeeSchemeID(int FeeSchemeID) 
    { 
     using(var db = new QualificationContext()) 
     { 
      var query = (from d in db.FeeZone 
         where (!(from b in db.FeeZoneScheme 
           where b.FeeSchemeID == FeeSchemeID 
           join c in db.FeeZone on b.FeeZoneID equals c.FeeZoneID 
           select c).Contains(d.FeeZoneID)) 
         select d).ToList(); 



      return query.ToList(); 
     } 

    } 

這是錯誤: enter image description here 非常感謝

回答

1

請嘗試如下所示。

from d in FeeZones 
where (!(from b in FeeZoneSchemes where b.FeeSchemeID == 1 
    join c in FeeZones on b.FeeZoneID equals c.FeeZoneID 
    select c.FeeZoneID).Contains(d.FeeZoneID)) 
select d 
+0

不,我得到的錯誤我有更新我的代碼上面請...非常感謝 – toxic

+0

@toxic請檢查我的更新。 – Sampath

+0

它返回我所有的記錄,而不是過濾的記錄,我只是在visual studio中調試... – toxic

4

試試這個代碼:

var query = from d in FreeZones 
      let unwantedZonesIds = FeeZoneSchemes.Where(b => b.FreeSchemeID == 1) 
               .Select(b => b.FreeZoneID) 
      where !unwantedZonesIds.Contains(d.FreeZoneID) 
      select d; 
2

使用Any而不是Contains

var query = (from d in db.FeeZone 
        where (!((from b in db.FeeZoneScheme 
          where b.FeeSchemeID == FeeSchemeID 
          join c in db.FeeZone on b.FeeZoneID equals c.FeeZoneID 
          select c).Any(x => x.FeeZoneID ==d.FeeZoneID)) 
        select d).ToList(); 
0

您可以使用下面的查詢。

 IList<FeeZones> lst = new List<FeeZones>() { new FeeZones() { FeeZoneID = 1 }, new FeeZones() { FeeZoneID =2 } }; 
     IList<FeeZoneSchemes> lstnew = new List<FeeZoneSchemes>(){new FeeZoneSchemes(){FeeSchemeID=1,FeeZoneID=1}}; 


     var res = (from d in lst 
        where !(
         from c in lstnew 
         join f in lst on c.FeeZoneID equals f.FeeZoneID 
         where c.FeeSchemeID == 1 && c.FeeZoneID == f.FeeZoneID 
         select f.FeeZoneID 
        ).Contains(d.FeeZoneID) 
        select d).ToList(); 

或者您可以使用Sql方式存在查詢如下。

var res = (from d in lst 
        where !(
         from c in lstnew 
         where c.FeeSchemeID == 1 && c.FeeZoneID == d.FeeZoneID 
         select c 
        ).Any() 
        select d).ToList(); 
相關問題