2014-07-15 125 views
0

我有一个DataTable,名为dt,它有两列,并且通过从CSV文件读取数据进行填充。这两列是Keys和它们各自的Descriptions大约7000行。将数据表与IList进行比较

现在我有IList<string>键,它只是键(与DataTable中的键相同)。

如何将IList<string>键与DataTable匹配,并检索最终输出为new DataTable,该输出只有与IList匹配的行?

回答

1

您可以使用:

DataTable filtered = dt.AsEnumerable() 
         .Where(r => list.Contains(r.Field<int>("id"))) 
         .CopyToDataTable(); 

您还可以创建一个HashSet<T>和使用,在您的查询。

List<int> list = new List<int>(); 
//.... ids in the list 

HashSet<int> hashSet = new HashSet<int>(list); 
DataTable filtered = dt.AsEnumerable() 
         .Where(r => hashSet.Contains(r.Field<int>("id"))) 
         .CopyToDataTable(); 
+1

感谢哈比卜它的伟大工程 – user2779848

0

在实体框架的情况下:

类DbItem { 公众诠释键{获得;组; } public int Value {get;组; }}

var keysInMemory = new List<int>(); // put your Keys here 
var values = new StringBuilder(); 
values.AppendFormat("{0}", keysInMemory[0]); 
for (var i = 1; i < keysInMemory.Count; i++) 
      values.AppendFormat(", {0}", keysInMemory[i]); 

var sql = string.Format(@"SELECT dt.Key Key, dt.Value Value FROM [dbo].[dt] where Key IN ({0})", values.ToString()); 

var result = await _dbContext.Database.SqlQuery<DbItem>(sql).ToListAsync(); 

注意, “包含” 与IQueryable的真的糟糕表现