如何使用表达式参数c#实现方法

时间:2013-05-08 09:02:27

标签: c# .net linq

我想创建一个这样的方法:

var result = database.Search<EntityType>(x=>x.Name, "Entity Name field value");
result = database.Search<EntityType>(x=>x.Id, "Entity Id field value");
result = database.Search<EntityType2>(x=>x.Id, "Entity2 Id field value");
result = database.Search<EntityTypeAny>(x=>x.FieldAny, "EntityAny FieldAny value");

如何实施此方法?

3 个答案:

答案 0 :(得分:10)

您可以使用Expression.Equal

将选择器和值转换为谓词
static IQueryable<TSource> Search<TSource, TValue>(
    this IQueryable<TSource> source,
    Expression<Func<TSource,TValue>> selector,
    TValue value)
{
    var predicate = Expression.Lambda<Func<TSource,bool>>(
        Expression.Equal(
            selector.Body,
            Expression.Constant(value, typeof(TValue))
        ), selector.Parameters);
    return source.Where(predicate);
}

然后你只需要做一些事情:

var result = database.SomeEntities.Search(x => x.SomeProp, "value");

如果您想从数据库中执行此操作,那么这取决于数据库;例如,使用LINQ-to-SQL,您可以添加其他方法:

static IQueryable<TSource> Search<TSource, TValue>(
    this System.Data.Linq.DataContext database,
    Expression<Func<TSource, TValue>> selector,
    TValue value) where TSource : class
{
    IQueryable<TSource> source = database.GetTable<TSource>();
    return Search(source, selector, value);
}

并使用:

var result = database.Search<SomeEntity, string>(x => x.SomeProp, "value");
坦率地说,我认为使用database.SomeEntities版本更清楚。

答案 1 :(得分:1)

我只能想到这个(带有2个通用参数)

    public static IEnumerable<TModel> Search<TModel, TValue>(
        Expression<Func<TModel, TValue>> expression,
        TValue value
    )
    {
        return new List<TModel>();
    }

使用

var result = Search<EntityType, int>(x => x.Id, 1);
var result2 = Search<EntityType, string>(x => x.Name, "The name");

你可以用对象替换TValue以避免第二个泛型参数,但我会坚持这一点。

顺便说一下。这与这个小助手一起很好用

public static class ExpressionHelpers
{
    public static string MemberName<T, V>(this Expression<Func<T, V>> expression)
    {
        var memberExpression = expression.Body as MemberExpression;
        if (memberExpression == null)
            throw new InvalidOperationException("Expression must be a member expression");

        return memberExpression.Member.Name;
    }
}

现在,您可以通过调用

获取此示例中的属性名称(Id order Name)
var name = expression.MemberName();

答案 2 :(得分:0)

你想要类型动态

public ReturnType Read<ReturnType>(string FieldName, object dfVal)
{
    if (Res.IsDBNull(Res.GetOrdinal(FieldName)))
        return dfVal;
    try {
        return (ReturnType)Res.GetValue(Res.GetOrdinal(FieldName));
    } catch (Exception ex) {
        return dfVal;
    }
}