如何使用未知字段创建lambda表达式?

时间:2015-01-19 23:30:04

标签: c# .net entity-framework dynamic lambda

我想动态构建lambda表达式,以便我可以使用未知数量的字段构建查询...我该如何实现?

我循环遍历一个对象,该对象包含添加到每个字段的Where子句的所有字段和值...

searcher = searcher.Where(f => f.fieldName.Contains(fieldValue));

即。伪代码:

foreach(var field in fields){
    searcher = searcher.Where(f => field.name.Contains(field.value));
}

如果我生活在这个石器时代,我会像这样伪代码:

var first = true;
string query = " SELECT * FROM TABLE WHERE ";
foreach(var field in fields){
    if(first){
        query += field.name + " LIKE '%" + field.value + "%' ";
    }else{
        query += " AND " + field.name + " LIKE '%" + field.value + "%' ";
    }

    first = false;
}

请告诉我,石器时代并不比现有技术更强大! ; - )

1 个答案:

答案 0 :(得分:0)

我希望这会有所帮助。

searcher = fields.Aggregate(searcher, (current, field) => current.Where(f => f.Name.Contains(f.Value)));