如何将 Linq 动态查询结果转换为自定义类?

发布于 2024-08-27 02:38:22 字数 672 浏览 13 评论 0原文

通常,我会这样做:

var a = from   p in db.Products
        where  p.ProductType == "Tee Shirt"
        group  p by p.ProductColor into g
        select new Category { 
               PropertyType = g.Key,
               Count = g.Count() }

但我有这样的代码:

var a = Products
        .Where("ProductType == @0", "Tee Shirt")
        .GroupBy("ProductColor", "it")
        .Select("new ( Key, it.Count() as int )");

我可以改变什么语法来产生相同的结果,即,如何从第二个 Linq 语句中进行类别投影?

我都知道git 相同,代表整个表记录,我将整个记录拉入只是为了进行计数。我也需要解决这个问题。 编辑:Marcelo Cantos 指出 Linq 足够聪明,不会提取不必要的数据。谢谢!

Normally, I do this:

var a = from   p in db.Products
        where  p.ProductType == "Tee Shirt"
        group  p by p.ProductColor into g
        select new Category { 
               PropertyType = g.Key,
               Count = g.Count() }

But I have code like this:

var a = Products
        .Where("ProductType == @0", "Tee Shirt")
        .GroupBy("ProductColor", "it")
        .Select("new ( Key, it.Count() as int )");

What syntax could I alter to produce identical results, i.e., how do I do a projection of Category from the second Linq statement?

I know in both that g and it are the same and represent the entire table record, and that I am pulling the entire record in just to do a count. I need to fix that too. Edit: Marcelo Cantos pointed out that Linq is smart enough to not pull unnecessary data. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡看悲欢离合 2024-09-03 02:38:22

为什么你必须这么做?由于在 GroupBy 调用后您仍然拥有所有信息,因此您可以轻松地执行此操作:

var a = Products
        .Where("ProductType == @0", "Tee Shirt")
        .GroupBy("ProductColor", "it")
        .Select(c => new Category { 
            PropertyType = g.Key, Count = g.Count() 
        });

Products 的类型仍应流经并可访问,并且常规分组/过滤不应改变流经扩展方法的类型。

Why would you have to do it at all? Since you still have all of the information after the GroupBy call, you can easily do this:

var a = Products
        .Where("ProductType == @0", "Tee Shirt")
        .GroupBy("ProductColor", "it")
        .Select(c => new Category { 
            PropertyType = g.Key, Count = g.Count() 
        });

The type of Products should still flow through and be accessible and the regular groupings/filtering shouldn't mutate the type that is flowing through the extension methods.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文