将表达式传递给linq的Select [英] Pass in an Expression to linq's Select

查看:102
本文介绍了将表达式传递给linq的Select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 linq-to-sql

我有很多不同的类都在执行相同的查询,但是对结果的预测略有不同.理想情况下,我希望能够将查询放在一个地方,并将投影传递到Select方法中.它适用于具体类型:

I have a lot of different classes all doing the same query, but projecting the results slightly differently. Ideally I'd like to be able to have the query in one place, and have the projection passed into the Select method. It works fine for concrete types:

public void GetResults() {
    var junk = db.SiteProducts.Select(Project());
}

public Expression<Func<DbEntities.SiteProduct, string>> Project() {
    return p => p.ProductAlert;
}

但是当我尝试返回匿名类型时,它会失败

But when I try to return an anonymous type, it fails

public void GetResults() {
    var junk = db.SiteProducts.Select(Project());
}

public Expression<Func<DbEntities.SiteProduct, TResult>> Project<TResult>() {
    return p => new { p.ProductAlert };
}

我完全理解为什么在第二种情况下泛型类型推断失败.但是,有没有一个窍门-缺少从头开始构建自己的表达式的机会-我想念能使它起作用的东西吗?

I fully understand why generic type inference is failing in the second case. But is there a trick—short of crafting my own Expressions from the ground up—I'm missing that could get this to work?

推荐答案

如果我正确理解了您的问题,则可以使用以下代码:

If I understand your question correctly you can use this code:

首先声明一种选择数据的方法,如下所示:

first declare a method for selecting your data like this:

public List<TResult> FindAll<TResult>(Func<Regions, TResult> selector) where TResult : class
    {
        using (RepositoryDataContext = new DataClasses1DataContext())
        {
                return RepositoryDataContext.Regions.Select<Regions, TResult>(selector).ToList<TResult>();

        }
    }

然后您可以构建如下的select语句:

then you can build your select statement like this:

Func<Regions, SelectAllRegion> select = r => new SelectAllRegion
        {
            RegionID = r.RegionID,
            RegionDescription = r.RegionDescription
        };

我的SelectAllRegion:

 public class SelectAllRegion
{
    public SelectAllRegion()
    {
    }
    public int RegionID { get; set; }
    public string RegionDescription { get; set; }
}

和区域是北翼的Region表.希望对您有帮助

and region is Region table in northwing.I hope this help you

这篇关于将表达式传递给linq的Select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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