我有一个将LINQ结果绑定到表单上的控件的函数。下面的代码有效,但我无法克服我应该为复制/粘贴方面打耳光的感觉。有人可以帮我解决这个问题吗?
谢谢!
private void BindDataToForm()
{
// Bind data to form
CaseNotesDataContext db = new CaseNotesDataContext();
Table<CN_MaintItem> caseNotesItems = db.GetTable<CN_MaintItem>();
// For each object
var contactType = from cType in caseNotesItems
where cType.CategoryID == 2
select cType.ItemDescription;
chkContactType.DataSource = contactType;
var contactLocation = from cLocation in caseNotesItems
where cLocation.CategoryID == 3
select cLocation.ItemDescription;
lkuContactLocation.Properties.DataSource = contactLocation;
var contactMethod = from cMethod in caseNotesItems
where cMethod.CategoryID == 4
select cMethod.ItemDescription;
lkuContactMethod.Properties.DataSource = contactMethod;
var contactWith = from cWith in caseNotesItems
where cWith.CategoryID == 5
select cWith.ItemDescription;
chkContactWith.DataSource = contactWith;
var domains = from d in caseNotesItems
where d.CategoryID == 6
select d.ItemDescription;
chkDomains.DataSource = domains;
}
答案 0 :(得分:3)
我不知道这是否真的能解决问题,但尝试:
public static class MyExtentsions {
public IQueryable<string> GetItemDescriptions(this Table<CN_MaintItem> table, int cat)
{
return from x in table
where x.CategoryID == cat
select x.ItemDescription;
}
}
所以你可以提取这样的信息:
using (CaseNotesDataContext db = new CaseNotesDataContext()) {
Table<CN_MaintItem> caseNotesItems = db.GetTable<CN_MaintItem>();
chkContactType.DataSource = caseNotesItems.GetItemDescriptions(2);
lkuContactLocation.Properties.DataSource = caseNotesItems.GetItemDescriptions(3);
// etc...
}
答案 1 :(得分:1)
诀窍是存储明确绑定控件所需的信息。您可以创建IDictionary<Control, Int32>
来存储每个控件的类别ID。然后迭代所有控件,在字典中查找id,最后在条目存在时绑定它。您可以通过创建一个以委托作为值的字典来扩展此方法。这允许您对不同的控件执行不同的查询。此外,您还可以使用Control.Tag
属性来存储此信息。
答案 2 :(得分:0)
您可以通过执行以下操作来“缩短”它:
IQueryable<string> GetDescriptions(int cat)
{
return from x in caseNotesItems
where x.CategoryID == cat
select x.ItemDescription;
}
然后:
chkDomains.DataSource = GetDescriptions(6);
...