2011-11-03 29 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等),它执行给你打电话的数据库服务器。

相关问题