2011-11-03 27 views
1

很抱歉的混亂主題行:)刪除從數據錶行,其中一個條目在其他DataTable

我想和我的數據表中的SQLlike查詢存在:S:我想要做這樣的事情

// Is named "BadValues" Rows contain: id1, id2 
DataTable tableReadFromFile = readFromFile(); 
// Is named "AllValues" Rows contain id1, id2 
DataTable tableReadFromSql = readFromSql 

DataTable resultTable = 
    tableReadFromFile.select("where AllValues.id1 not in (select id1 from BadValues) and AllValues.id2 not in (select id2 from BadValues)"); 

所以,如果我的 「BadValues」 表是這樣的:

id1 id2 
0 1 
10 11 
20 21 

和我的 「AllValues」 表是這樣的:

id1 id2 
0 1 
0 2 
1 1 
10 11 
10 12 
12 11 
20 21 
20 22 
22 21 

我想resultTable看起來像這樣:

id1 id2 
0 2 
1 1 
10 12 
12 11 
20 22 
22 21 

換句話說:如果對ID1,ID2表中的「BadValues」和「AllValues」的存在我想刪除它們,以便它們不存在於結果表中。

如果在SQL數據庫中存在表「BadValues」,那麼在SQL中這樣做會相當簡單,但由於它是從不可能的文件加載的。

現在,我循環遍歷「BadValues」中的所有行,並使用設置的id1和id2值構造單個SQL查詢。由於我有相當多的數據,這非常耗時。

任何提示被讚賞!

回答

0

使用Linq to dataset

var badValues = new HashSet<Tuple<int, int>>(
        tableReadFromFile.AsEnumerable(). 
            Select(row => 
             new Tuple<int, int>(row.Field<int>("id1"), row.Field<int>("id2")))); 

var result = tableReadFromSql.AsEnumerable(). 
            Where(row => !(badValues.Contains(
            new Tuple<int, int>(row.Field<int>("id1"), row.Field<int>("id2"))))); 

第一條語句創建基本代表了壞值的元組的一個HashSet。

第二個在第二個表中搜索id不在散列集中的行。

+0

這個伎倆!謝謝 :) – user1028037

1

我想這會做到這一點:

DataTable tblBadValues; // filled however 
DataTable tblAllValues; // filled however 
tblBadValues.Merge(tblAllValues); // this will add to tblBadValues all records 
            // that aren't already in there 
DataTable tblResults = tblBadValues.getChanges(); // this will get the records 
    // that were just added by the merge, meaning it will return all the records 
    // that were originally in tblAllValues that weren't also in tblBadValues 
tblBadValues.RejectChanges(); // in case you need to re-use tblBadValues 
+0

感謝您的回覆!我試過了,但我不得不爲它設置主鍵: DataColumn [] badValuesKeys = new DataColumn [2]; badValuesKeys [0] = badValues.Columns [「id1」]; badValuesKeys [1] = badValues.Columns [「id2」]; badValues.PrimaryKey = badValuesKeys; 我仍然有問題。 badValues.GetChanges()返回整個合併表。我在嘗試合併之前嘗試調用badValues.AcceptChanges(),但沒有運氣。 – user1028037

0

我有一個想法,但你必須做LINQ to SQL。

var query = from data in AllObjects          
        select data; 

foreach (DataObject o in BadData) 
{ 
    DataObject temp = o; 
    query = query.Where(x => !((x.id1 == temp.id1) && (x.id2 == temp.id2))); 
} 
//query now contains the expression to get only good rows. 

只有當query被迭代(或.ToArray等),它執行給你打電話的數據庫服務器。

相關問題