从自动生成百万行的c# dll数据库中获取低库存
本文关键字:数据库 dll 获取 自动生成 百万 | 更新日期: 2023-09-27 18:07:48
我有一个数据库(c#, dll),它只包含一个表,自动生成百万行。
我一次只能得到一行。表的列是:int ItemID, string category, string model, string Brand
).
如果两个项目具有相同的category, brand, model
,则它们相同。我想找出所有类型的低库存商品,低库存是指该类型的商品剩余的数量小于等于两种。
这是我为此写的代码,但它花了2或3个小时来执行,它没有给我正确的结果。我怎么解决这个问题?
public DataTable getLowStock()
{
DataTable dt = new DataTable();
object[,] arr=new object[1000000,4];
int index=0;
int rows;
rows = db.NumRows;
int[] IdArray;
IdArray = db.GetItemIDList(0, rows - 1);
string Category, Brand, Model, Condition, Location, Notes;
DateTime ReceivedDate, LastUpdated;
int Weight;
double PurchasePrice, SellingPrice;
for (int a = 0; a < IdArray.Length; a++)
{
Console.WriteLine(a);
db.GetItemRecord(IdArray[a], out Category, out Brand, out Model,
out ReceivedDate, out Weight, out Condition, out Location,
out PurchasePrice, out SellingPrice, out Notes, out LastUpdated);
if (a == 0)
{
arr[0, 0] = Category;
arr[0, 1] = Brand;
arr[0, 2] = Model;
arr[0, 3] = 1;
index++;
}
else
{
for (int i = 0; i < index; i++)
{
if ( ( arr[i,2].ToString()==Model)&& (arr[i,1].ToString()==Brand) && (arr[i,0].ToString()==Category ) )
{
arr[i, 3] = (Int32)arr[i, 3] + 1;
}
}
arr[index,0]=Category;
arr[index,1]=Brand;
arr[index,2]=Model;
arr[index, 3] = 1;
index++;
}
}
dt.Columns.Add("Category", typeof(string));
dt.Columns.Add("Model", typeof(string));
dt.Columns.Add("Brand", typeof(string));
dt.Columns.Add("count", typeof(int));
for (int i = 0; i < index; i++) {
Console.WriteLine("i="+i);
if((int)arr[i,3]<3){
dt.Rows.Add(arr[i,0].ToString(),arr[i,2].ToString(),arr[i,1].ToString(),(int)arr[i,3]);
}
}
return dt;
}
做到这一点的最好方法是使用实际的数据库吗?然后可以用SQL进行查询,这将比查询内存中的数据表快1000倍。
不是获取整个表,我建议您执行sql聚合并仅获取聚合:
SELECT category, model, brand, COUNT(*)
FROM table
GROUP BY category, model, brand
HAVING COUNT(*) >= 2
那么,由于几个原因,您的代码非常慢,但主要原因是它是二次的。所以100万的平方等于1万亿次操作,这是相当慢的。
如果必须自己进行聚合,则必须使用合适的容器,如set或哈希表,而不是数组。这样,您将在O(n)(使用一个好的哈希表)或O(n log n)(使用一个集合)中执行,而不是0(n^2)。