[英]Remove rows from a DataTable where an entry exist in another DataTable
抱歉,主題行混亂:)
我想用我的DataTable:s做一個類似SQL的查詢:我想做這樣的事情
// 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
換句話說:如果在表“ BadValues”和“ AllValues”中存在id1,id2對,則我希望將其刪除,以使它們不存在於結果表中。
如果表“ BadValues”將存在於SQL數據庫中,則在SQL中這樣做非常簡單,但是由於無法從文件中進行加載。
現在,我遍歷“ BadValues”中的所有行,並使用設置的id1和id2值構造單個SQL查詢。 由於我有很多數據,因此非常耗時。
任何提示,不勝感激!
我認為這可以做到:
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
使用Linq進行數據集 :
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")))));
第一條語句基本上會創建表示不良值的元組的哈希集。
第二個在第二個表中搜索ID不在哈希集中的行。
我有一個主意,盡管您必須對SQL執行LINQ。
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
等)時,它才會執行對數據庫服務器的調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.