如何实现方法与前pression参数C# [英] How to implement method with expression parameter c#

查看:159
本文介绍了如何实现方法与前pression参数C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建这样一个方法:

I want to create a method like this:

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");

我怎样才能实现这个方法?

How can I implement this method?

推荐答案

您可以打开一个选择器和值转换为predicate使用防爆pression.Equal

You can turn a selector and value into a predicate using 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);
}

接下来,你需要做的是这样的:

Then you just need to do something like:

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

如果您想从的做数据库的,那么这要看是什么数据库的的;例如,使用LINQ到SQL您可以添加一个额外的方法:

If you want to do it from the database, then that depends on what the database is; for example, with LINQ-to-SQL you could add an additional method:

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 的版本,虽然。

这篇关于如何实现方法与前pression参数C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆