英文:
C# WPF Reuseable combobox populate method
问题
以下是代码的翻译部分:
我有以下代码来使用LookupItem数据服务来填充一个ConboBox。 是否有办法通过能够传递模型/类名和用于DisplayMember的'Name'属性来使此代码可重用,即在下面的情况下'GradeName'。
非常感谢。
public async Task<IEnumerable<LookupItem>> GetGradeLookupAsync()
{
using (var ctx = _contextCreator())
{
return await ctx.Grades.AsNoTracking()
.Select(g =>
new LookupItem
{
Id = g.Id,
DisplayMember = g.GradeName
})
.ToListAsync();
}
}
英文:
I have the following code to populate a ConboBox using a LookupItem data service. Is there any way to make this code reuseable by being able to pass in the Model/Class name and the 'Name' property which is used for the DisplayMember, i.e. in the case below 'GradeName'.
Many Thanks.
public async Task<IEnumerable<LookupItem>> GetGradeLookupAsync()
{
using (var ctx = _contextCreator())
{
return await ctx.Grades.AsNoTracking()
.Select(g =>
new LookupItem
{
Id = g.Id,
DisplayMember = g.GradeName
})
.ToListAsync();
}
}
答案1
得分: 1
你可以尝试使用通用方法。类似这样的:
public async Task<IEnumerable<LookupItem>> GetGradeLookupAsync<T>(
Func<MyContext, IList<T>> dbSet,
Func<T, int> idProperty,
Func<T, string> nameProperty)
{
using (var ctx = _contextCreator())
{
var set = dbSet(ctx);
return set
.Select(g =>
new LookupItem
{
Id = idProperty(g),
DisplayMember = nameProperty(g)
})
.ToListAsync();
}
}
示例用法:
await GetGradeLookupAsync(ctx => ctx.Grades, g => g.Id, g => g.GradeName);
英文:
You could try with a generic method. Something like this:
public async Task<IEnumerable<LookupItem>> GetGradeLookupAsync<T>(
Func<MyContext, IList<T>> dbSet,
Func<T, int> idProperty,
Func<T, string> nameProperty)
{
using (var ctx = _contextCreator())
{
var set = dbSet(ctx);
return set
.Select(g =>
new LookupItem
{
Id = idProperty(g),
DisplayMember = nameProperty(g)
});
.ToListAsync();
}
}
Sample usage:
await GetGradeLookupAsync(ctx => ctx.Grades, g => g.Id, g => g.GradeName);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论