簡體   English   中英

比較2個數據表並使用2個條件選擇不在第二個表中的行

[英]Compare 2 DataTables and Select Rows Not in 2nd table Using 2 Criteria

我需要此功能用於事務表。 我的數據表看起來像這樣。

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代碼(或其他代碼),則數據庫將包含數據庫中的記錄,而不是文本文件中的記錄。

RecordsNotInTextFile-表

a_code | b_code
AB     | 001
AC     | 001

我已經有一個LINQ代碼,但是它僅使用一個ID進行比較。

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.";

如果您需要過濾掉兩個異常,最簡單的方法是將兩個.Except()調用鏈接到LINQ表達式中。

從您的評論看來,您對LINQ的操作原理並不熟悉。 如果您想了解,我建議您閱讀Jon Skeet的“ Edulinq”系列 ,其中他重新實現了標准的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的文章,並特別注意Select and Except ,您應該從中了解LINQ如何足夠有效地完成您所需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM