提高 C# 中 DataTable 的查询性能
Increasing the query Performance on DataTable in C#
代码正在尝试从查找 table 中查找值。为了提高代码的性能,我决定给查找函数一个排序的 table 而不是原来的 table。我听说创建数据视图有助于提高 select 的性能,但我不相信实现,因为我再次将数据视图转换为 table。所以我不明白它是如何帮助的。性能几乎没有差异,但对于更大的数据库,它可能会有所不同。如果我做对或错或如何提高性能,有人可以向我提供建议。
创建数据视图
List<DataView> dvTablesLookup = null;
List<DataTable> dtTablesLookup = null;
dvTablesLookup = datatablesLookup.Select(dt => new DataView(dt)).ToList();
dvTablesLookup.ForEach(x => x.Sort = sortLookup);
dtTablesLookup = dvTablesLookup.Select(dv => dv.ToTable()).ToList();
调用函数
result.AddRange(this.GetValueFromLookup(filter, lookupValueField.StringValue, dtTablesLookup[i]));
查找功能。该函数将 lookuptable 作为参数。
private object[] GetValueFromLookup(MultipleKeyConditionBuilder filter, string lookupValueField, DataTable datatableLookup)
{
object[] result;
DataRow[] rows = datatableLookup.Select(filter.Condition);
result = new object[rows.Count()];
for (int i = 0; i < rows.Count(); i++)
{
result[i] = rows[0][lookupValueField];
}
return result;
}
使用字典 我意识到我的数据中有很多重复项,并且重复执行相同的查询得到相同的结果。所以我决定使用字典,它将性能从几分钟显着提高到几秒。
使用视图:视图的好处完全取决于数据和查询条件。由于查询的目的是查找,视图对我没有任何好处,相反,对于更大的记录,它需要更多的时间。
代码正在尝试从查找 table 中查找值。为了提高代码的性能,我决定给查找函数一个排序的 table 而不是原来的 table。我听说创建数据视图有助于提高 select 的性能,但我不相信实现,因为我再次将数据视图转换为 table。所以我不明白它是如何帮助的。性能几乎没有差异,但对于更大的数据库,它可能会有所不同。如果我做对或错或如何提高性能,有人可以向我提供建议。
创建数据视图
List<DataView> dvTablesLookup = null;
List<DataTable> dtTablesLookup = null;
dvTablesLookup = datatablesLookup.Select(dt => new DataView(dt)).ToList();
dvTablesLookup.ForEach(x => x.Sort = sortLookup);
dtTablesLookup = dvTablesLookup.Select(dv => dv.ToTable()).ToList();
调用函数
result.AddRange(this.GetValueFromLookup(filter, lookupValueField.StringValue, dtTablesLookup[i]));
查找功能。该函数将 lookuptable 作为参数。
private object[] GetValueFromLookup(MultipleKeyConditionBuilder filter, string lookupValueField, DataTable datatableLookup)
{
object[] result;
DataRow[] rows = datatableLookup.Select(filter.Condition);
result = new object[rows.Count()];
for (int i = 0; i < rows.Count(); i++)
{
result[i] = rows[0][lookupValueField];
}
return result;
}
使用字典 我意识到我的数据中有很多重复项,并且重复执行相同的查询得到相同的结果。所以我决定使用字典,它将性能从几分钟显着提高到几秒。
使用视图:视图的好处完全取决于数据和查询条件。由于查询的目的是查找,视图对我没有任何好处,相反,对于更大的记录,它需要更多的时间。