我有以下函數返回Model
。需要時間說是否有2000 employees
,需要3-4 minutes to return data
。我其實想要optimize this function
。我已經完成了下面的代碼中包含的一些東西,但仍然需要很多時間。C#優化代碼
using (var ctx = new ApplicationDbContext(schemaName))
{
List<Employee> list = new List<Employee>();
Employee mod = new Employee();
var data = ctx.Employee.Where(a => a.Company == comp && a.Status == Live)
.Select(a => new
{
Id = a.Id,
Code = a.Code,
FName = a.FName,
DateOfJoining = a.DateOfJoining,
Category = a.Category,
Department = a.Department,
Designation = a.Designation;
})
.ToList();
var loadValues = ctx.CValue.Where(c => c.Company == comp).ToList();
foreach (var item in data)
{
mod = new Employee();
mod.Id = item.Id;
mod.Code = item.Code;
mod.FName = item.FName;
mod.DateOfJoining = item.DateOfJoining;
mod.Category = item.Category;
mod.Designation = item.Designation;
mod.Department = item.Department;
int designation = (item.Designation == null) ? 0 : item.Designation;
int department = (item.Department == null) ? 0 : item.Department;
if (designation != 0)
mod.DesignationString = loadValues.Where(c => c.CompanyId == comp && c.Id == designation).Select(c => c.ComboValue).FirstOrDefault();
if (department != 0)
mod.DepartmentString = loadValues.Where(c => c.Company == comp && c.Id == department).Select(c => c.ComboValue).FirstOrDefault();
list.Add(mod);
}
return list;
}
}
我認爲這是需要時間的foreach
循環。任何解決方法?如何優化上述代碼?
如何填充ctx?您提供的代碼不應該花費很長時間 –
如何使用秒錶逐行測量時間? – 2016-07-05 10:59:42
_「我認爲這是需要時間的'foreach'循環」_找出肯定的答案。有這樣的事情的好工具,例如(隨機選擇):[ANTS](http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/)。在開始優化之前,您需要知道哪個位比較慢。 –