对于令人困惑的主题行感到抱歉:)
我想用我的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 :(得分: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
答案 1 :(得分:0)
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不在hashset中的行。
答案 2 :(得分: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
等)时才会执行对数据库服务器的调用。