2009-12-14 79 views
1

我有一個方法:僅在部分代理的LINQ中有兩種方法不同?

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 

如何爲此創造優雅,面向對象的解決方案嗎? 我應該使用委託還是其他的東西?

回答

-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); 
     } 
    } 
} 
+0

這就是我建議的Func ,其中TReturn的類型是bool,相當於Predicate 。 – 2009-12-14 11:13:02

+0

是的,所以我也給了你一個觀點 – 2009-12-16 10:38:01

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... 
} 

則調用該方法氦的方式說。

+0

是的,但如果我有什麼未來6點在一部分改變的方法呢? – 2009-12-14 09:24:12

+0

當我寫DoctorTable.Rows。我沒有通過Intellisense得到它在哪裏,所以它不存在 – 2009-12-14 09:57:14

+0

當我這樣做:在DoctorTable中選擇DataRow醫生>行where(rows => whereClause(d)select doctor.ID我得到錯誤「無法轉換lambda表達式到類型布爾因爲它是不是代表類型 – 2009-12-14 09:58:52

0

您可以參數化您的方法,以便將條件作爲從DataRow到bool的函數。

比你能打電話

GetDoctorsIDs(doctor => doctor.Age > 30); 

GetDoctorsIDs(doctor => doctor.Cost > 30000); 
+0

這個解決方案你能說得更具描述性嗎? – 2009-12-14 09:28:03

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); 
     } 
    } 
} 
相關問題