我有一个方法:
internal List<int> GetOldDoctorsIDs
{
var Result = from DataRow doctor in DoctorTable.Rows
where doctor.Age > 30
select doctor.ID
List<int> Doctors = new List<int>();
foreach (int id in Result)
{
//Register getting data
Database.LogAccess("GetOldDoctorsID: " + id.ToString());
if (Database.AllowAccess(DoctorsTable, id))
{
Doctors.Add(id);
}
}
}
所以这会让老医生做其他事情。现在我想创建方法GetExpensiveDoctors。它将如上所示,但代替:
where doctor.Age > 30
我会:
where doctor.Cost > 30000
如何为此创建优雅,面向对象的解决方案? 我应该使用委托还是其他东西?
答案 0 :(得分:3)
如果修改方法以包含谓词参数(见下文),则可以根据氦气的示例使用您需要的任何过滤器调用该方法。
internal List<int> GetDoctorsIDs(Predicate<DataRow> doctorFilter)
{
var Result = from DataRow doctor in DoctorTable.Rows
where doctorFilter(doctor)
select doctor.ID
List<int> Doctors = new List<int>();
foreach (int id in Result)
{
//Register getting data
Database.LogAccess("GetOldDoctorsID: " + id.ToString());
if (Database.AllowAccess(DoctorsTable, id))
{
Doctors.Add(id);
}
}
}
答案 1 :(得分:0)
您可以有选择地添加where子句,例如:
var Result = from DataRow doctor in DoctorTable.Rows
select doctor.ID;
if(getByAge) {
Result=Result.Where(doctor => doctor.Age>30);
} else {
Result=Result.Where(doctor => doctor.Cost>30000);
}
其中getByAge
将是您方法的布尔参数。
修改即可。如果你需要参数化where子句,那么这样的东西应该有效:
internal List<int> GetOldDoctorsIDs(Func<Doctor, bool> whereClause)
{
var Result = DoctorTable.Rows.Where(d => whereClause(d)).Select(d => d.ID);
//etc...
}
然后你按照氦气说的方式调用方法。
答案 2 :(得分:0)
您可以参数化您的方法,以便将条件作为从DataRow到bool的函数。
比你可以打电话
GetDoctorsIDs(doctor => doctor.Age > 30);
或
GetDoctorsIDs(doctor => doctor.Cost > 30000);
答案 3 :(得分:-1)
我设法以这种方式做到了这一点:
internal List<int> GetOldDoctorsIDs()
{
return GetDoctorsIDs((doctor) => doctor.Age > 30);
}
internal List<int> GetExpensiveDoctorsIDs()
{
return GetDoctorsIDs((doctor) => doctor.Cost > 30000);
}
internal List<int> GetDoctorsIDs(Func<DataRow, bool> Condition)
{
var Result = from DataRow doctor in DoctorTable.Rows
where Condition(doctor)
select doctor.ID
List<int> Doctors = new List<int>();
foreach (int id in Result)
{
//Register getting data
Database.LogAccess("GetOldDoctorsID: " + id.ToString());
if (Database.AllowAccess(DoctorsTable, id))
{
Doctors.Add(id);
}
}
}