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

时间:2010-03-29 06:33:10

标签: c# linq dynamicquery

通常,我这样做:

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语句中对Category进行投影?

我知道 g 是相同的并代表整个表记录,而我正在拉动整个记录伯爵。我也需要解决这个问题。编辑:Marcelo Cantos指出Linq非常聪明,不会提取不必要的数据。谢谢!

1 个答案:

答案 0 :(得分:1)

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

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

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

相关问题