我想從數據庫中獲取業務模型實體,然後迭代它們以搜索字符串。但是,在我的本地主機上,該操作大約需要7 to 9 seconds for 500 objects
。從數據庫中取出的模型對象緩慢的C#迭代
public List<FileFolder> SearchFolders(int id, string searchString)
{
/* Placeholder that references folders that passes search criteria */
List<FileFolder> addedFolders = new List<FileFolder>();
/* Get the folder with specified id, also include Folders
* that this folder has. No problem here works perfectly fine
* and fast */
FileFolder folder = dbSet.Include("Folders").
.Where(q => q.FileFolderID == id)
.ToList().FirstOrDefault();
/* This takes too much time as I mention, up to 9 seconds
* for 500 Folders */
foreach (FileFolder f in folder.Folders)
{
if (f.Name.Contains(searchString))
{
addedFolders.Add(f);
}
}
return addedFolders;
}
我將我提取的數據轉換爲List,所以我可以安全地說所有的數據現在在內存中?所以foreach循環不應該在訪問文件夾時進行更多的數據庫調用。我也檢查了.Include
方法,它工作正常。
這種緩慢的迭代可能是什麼原因?
謝謝。
其ToList或FirstOrDefault。你爲什麼需要兩個?另外爲什麼不使用Parallel.ForEach? – Dimitri 2012-07-13 23:58:33
我刪除了ToList謝謝。從來沒有使用過Parallel.ForEach,我會考慮它,但不是它只需要太多的500個對象? – 2012-07-14 00:02:23
該機器執行的規格是什麼? – Dimitri 2012-07-14 00:04:11