LINQ查询不同的数据集,基于输入参数



我已经纠结这个问题很长一段时间了,我真的很想知道这是否可能。这是我当前的代码,但我真的不喜欢使用开关箱。有办法绕过它吗?

public async Task<RequestOutputModel> SearchById(int id, string category, CancellationToken cancellationToken)
{
RequestOutputModel query;
switch (category)
{
case "RequestTypeOne":
query = await this.mapper
.ProjectTo<RequestTypeOneOutputModel>(this
.Data
.RequestTypeOne
.Where(e => e.Id == id))
.FirstOrDefaultAsync(cancellationToken);
break;
case "RequestTypeTwo":
query = await this.mapper
.ProjectTo<RequestTypeTwoOutputModel>(this
.Data
.RequestTypeTwo
.Where(e => e.Id == id))
.FirstOrDefaultAsync(cancellationToken);
break;

您可以创建Dictionary<string, Expression<Func<Entity, bool>>>(或Dictionary<string, Func<CollectionItem, bool>>用于LINQ to Objects)并使用它代替if/elseswitch/case

private conditions = new Dictionary<string, Expression<Func<YourLinqEntityClass, bool>>>() {
{ "Q", /* cond Q */ },
{ "W", /* cond W */ },
{ "E", /* cond E */ },
// (...)
{ "P", /* cond P */ }
}
IEnumerable<list> function()
{
if(conditions.ContainsKey(category))
return db.Entities.Where(conditions(category));
return db.Entities;
}

相关内容

  • 没有找到相关文章

最新更新