【发布时间】:2017-07-14 14:04:29
【问题描述】:
有一个要求。我有一项 excel 导入功能,可将数据从 excel 文件添加到数据库。我需要在导入前添加一个过滤器来检查数据。假设有一个像 3:44-5:87-1:345 这样的值。 在导入之前,我需要验证这些数据是否有效 -
->3, 5, 1 应该存在于表T1中
->44、87、345,应该存在于表T2中。
如果两个条件匹配数据都应该被验证为正确
当前代码是这样的
string test = "3:44-5:87-1:345";
var attributes = test.Split(new[] { "-" },
StringSplitOptions.RemoveEmptyEntries);
if (attributes.Length != 0)
{
foreach (var attribute in attributes)
{
var attArray = attribute.Split(new[] { ":" },
StringSplitOptions.RemoveEmptyEntries);
if (attArray.Length >= 2)
{
int key = Convert.ToInt32(attArray[0].ToString())
int value = Convert.ToInt32(attArray[1].ToString())
//Call db to check if key exist
if(KeyExist)
{
//Call db to check if value exist for the key
if(ValueExist)
{
//CODE here to import data to datatabse
}
}
}
}
}
对于上述示例数据,它将对 3 个 Key(3, 5,1) 进行 3 次调用,对 3 个 Value(44, 87,345) 进行 3 次调用。因此,如果 excel 表中有 100 行,我可能最终会调用数千个数据库。 如何优化?
【问题讨论】:
-
是
T1中的每个x与T2中的一个y的组合是唯一的,或者T1中的一个条目可以“连接”到@ 中的几个不同条目987654327@(反之亦然)? -
为什么不在 OleDB 中调用 Reader 并将每个结果存储在 Dictionary
中,然后迭代字典,这样你只需要调用两次检查 Excel 表格。 -
根据答案,您可以使用两个
Dictionaries(T1=>T2和T2=>T1) 或两个Lookups(T1) =>Group of T2和T2=>Group of T1) -
100 行将是 200 次数据库调用,而不是数千次。
-
@Corak,可能有关系。所以 T1 的一个实体将连接到 T2 的多个实体
标签: c# mysql asp.net coding-style