我有一个具有IEnumerable的函数,它将循环建立一个字符串的记录列表。当我只返回一个对象时,我也想使用相同的功能。在中间层,有两个函数,一个返回列表,另一个返回对象。
我是否必须构建一个可以接收该对象的新函数?
public List<Model.Disease> GetDisease()
{
var Disease = (from Diseases in db.Diseases
select new Model.Disease
{
DiseaseId = Diseases.DiseaseId,
DiseaseName = Diseases.DiseaseName,
drug = (from d in db.Drug
where (Diseases.DiseaseId == d.DiseaseId
select new drug
{
DrugId = d.drug,
DrugName = d.drugName
}).OrderBy(m => m.DrugName).ToList(),
}).OrderBy(d => d.DiseaseName).ToList();
return Disease;
}
}
public List<Model.Disease> GetDiseaseById(Guid DiseaseId)
{
var Disease = (from Diseases in db.Diseases
select new Model.Disease
{
DiseaseId = Diseases.DiseaseId,
DiseaseName = Diseases.DiseaseName,
drug = (from d in db.Drug
where (Diseases.DiseaseId == d.DiseaseId && d.DrugId ==
1)
select new drug
{
DrugId = d.drug,
DrugName = d.drugName
}).OrderBy(m => m.DrugName).ToList(),
}).OrderBy(d => d.DiseaseName).ToList().FirstOrDefault();
return Disease;
}
}
private string BuildreimbursementDisplay(IEnumerable<ReimbursementDisease> displayList)
答案 0 :(得分:1)
您应该能够执行以下操作。
public Model.Disease GetFirstDisease()
{
return GetDisease().FirstOrDefault();
}
类似的东西也可以
public Model.Disease GetDiseaseById(Guid DiseaseId)
{
return GetDisease().Where(x => x.DiseaseId == DiseaseId).FirstOrDefault();
}
如果您尝试仅使用一个函数“看中”或使其变得“简单”,请不要。重用很重要(就像我在上面所做的一样),但是无缘无故地使其变得非常复杂只会使代码变糟。要花哨的话-使其简单易用,这样可以更轻松地维护和查找错误。
答案 1 :(得分:0)
从外观上,您已经有2种方法。得到疾病清单的人
公共列表GetDisease()
又是一名患有疾病的人
public Model.Disease GetDiseaseById(Guid DiseaseId)
考虑到您询问是否可以对单个疾病和疾病列表重用BuildreimbursementDisplay(IEnumerable displayList),并且您对它的工作方式感到满意-是的,您可以:
var disease = GetDiseaseById([disease_guid]);
string result = BuildreimbursementDisplay(new List<Model.Disease>().Add(disease));
这实际上会将单一疾病转换为仅包含一个成员的列表。不理想,但是我可以假设BuildreimbursementDisplay会执行以下操作:
string BuildreimbursementDisplay(List<Model.Disease> diseases)
{
string foo ="";
foreach (var disease in diseases)
{
foo += <...>;
}
return foo;
}
因此它只会循环一次。
注意:您需要检查是否有疾病==无效的情况。