【问题标题】:Compare datatable to IList将数据表与 IList 进行比较
【发布时间】:2014-09-05 19:07:24
【问题描述】:
我有一个名为dt 的DataTable,它有两列,通过从 CSV 文件中读取数据来填充。这 2 列是 Keys 和它们各自的 Descriptions 大约 7000 行。
现在我有了IList<string> 键,它只是键(与DataTable 中的键相同)。
如何将IList<string> 键与DataTable 匹配并检索最终输出为new DataTable,其中只有与IList 匹配的行?
【问题讨论】:
标签:
c#
wpf
linq
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();
【解决方案2】:
在实体框架的情况下:
类 DbItem
{
公共 int 键 { 获取;放; }
公共 int 值 { 获取;放; }
}
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 的“包含”性能真的很差