如何将 Linq 动态查询结果转换为自定义类?
通常,我会这样做:
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 语句中进行类别投影?
我都知道g 和 it 相同,代表整个表记录,我将整个记录拉入只是为了进行计数。我也需要解决这个问题。 编辑: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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么你必须这么做?由于在 GroupBy 调用后您仍然拥有所有信息,因此您可以轻松地执行此操作:
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:
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.