2015-09-07 50 views
1

我需要此功能用於事務表。我的數據表看起來像這樣。比較2個數據表和選擇行不在第2個表中使用2個條件

RecordsInDatabase-表

a_code | b_code 
AB  | 001 
AB  | 002 
AC  | 001 

RecordsInTextFile-表

a_code | b_code 
AB  | 002 
AC  | 005 
AC  | 009 

我需要用兩個ID,a_codeb_code比較。 因此,如果我運行LINQ代碼(或其他),datable將包含數據庫中的記錄,但不包含在文本文件中。

RecordsNotInTextFile-表

a_code | b_code 
AB  | 001 
AC  | 001 

我已經有一個LINQ代碼,但它僅使用一個ID比較。我是LINQ的新手,所以請和我一起裸照。

DataTable affixesInDatabase = affixDAO.SelectAllAffix(); 
      IEnumerable<string> affixesNotInTextFile = affixesInDatabase.AsEnumerable().Select(r => r.Field<string>("affix_code")) 
       .Except(affixesInTextFile.AsEnumerable().Select(r => r.Field<string>("affix_code"))); 
      if (affixesNotInTextFile.Any()) 
      { 
       DataTable affixesToBeDeleted = (from row in affixesInDatabase.AsEnumerable() 
               join id in affixesNotInTextFile 
               on row.Field<string>("affix_code") equals id 
               select row).CopyToDataTable(); 
       foreach (DataRow dr in affixesToBeDeleted.Rows) 
       { 
        affixDAO.DeleteAffix(dr[0].ToString()); 
       } 
      } 
      return "Affix data successfully edited."; 

謝謝!

回答

0

如果您需要篩選兩個例外,最簡單的方法是將兩個.Except()調用鏈接到您的LINQ表達式中。

從您的評論看來,您並不熟悉LINQ運行的原則。如果你想了解,我建議閱讀Jon Skeet's "Edulinq" series,他在其中重新實現了標準的LINQ查詢操作符,並解釋了它在所有操作中的工作原理。但是,下面是簡短版本:

LINQ是一組擴展方法,它們對可枚舉的序列(即IEnumerable<T>)進行操作。每種方法都將一個序列作爲輸入並應用一些操作,其中大多數將產生一個新的序列作爲輸出。 (有一些是產生一個單一的值來代替,但不是我們正在處理的人。)因此,這裏是你的查詢是這樣做的:

IEnumerable<string> affixesNotInTextFile = //assignment. You know how that works 
affixesInDatabase //our base sequence that we're starting from 
.AsEnumerable() //ensure that we're working with an IEnumerable, not an IQueryable 
.Select() //transform the sequence from the original objects to a sequence of Field<string> values from the original objects 
.Except() //filter out of the transformed sequence anything that's in *this* sequence 

Except()產生一個新的序列,所以你可以鏈接其他.Except()在將會進一步過濾序列的表達式的末尾。閱讀Edulinq的帖子,並特別注意SelectExcept上的帖子,並且您應該瞭解LINQ如何滿足您的需求。

+0

如何?我對LINQ相當陌生,並且也從SO獲得了我的代碼。 –

+0

@JeanoErmitaño編輯提供更多指導。 –

+0

感謝您提供鏈接。非常感激。當我自己解決問題時,我會回覆你。謝謝! –