MVC3查询子句自定义查询

时间:2012-07-28 04:28:22

标签: c# linq

First Table
+--------+------------+-------+
| type   | variety    | price |
+--------+------------+-------+
| apple  | gala       |  2.79 | 
| apple  | fuji       |  0.24 | 
| apple  | limbertwig |  2.87 | 
| orange | valencia   |  3.59 | 
| orange | navel      |  9.36 | 
| pear   | bradford   |  6.05 | 
| pear   | bartlett   |  2.14 | 
| cherry | bing       |  2.55 | 
| cherry | chelan     |  6.33 | 
+--------+------------+-------+
Second Table
+--------+----------+
| type   | minprice |
+--------+----------+
| apple  |     0.24 | 
| cherry |     2.55 | 
| orange |     3.59 | 
| pear   |     2.14 | 
+--------+----------+
select type, min(price) as minprice
from fruits
group by type;

第一个表是我拥有的数据的示例,第二个表是我想从第一个表中得到的数据。

我正在使用GenericRepository/UnitOfwork从存储库中获取数据。

repository.fruitRepository.Get().GroupBy(m => m.type);

但我只能获得类型字段,但我希望获得更多字段。

我是否需要在groupby之前使用select子句?如果是,我该如何选择更多字段?

1 个答案:

答案 0 :(得分:0)

GroupBy方法返回更多数据,但它以可枚举的形式返回...您可以通过GroupBy之后的Select来提取您想要的数据...

repository.fruitRepository.Get()
    .GroupBy(m => m.type)
    .Select(m => new { type = m.Key, minPrice = m.Min(f => f.Price) });

或者如果您更喜欢LINQ语句:

var result = from x in repository.fruitRepository.Get()
             group x by x.type into typeGroup
             select new
             {
                 type = typeGroup.Key,
                 minPrice = typeGroup.Min(item => item.Price)
             };
相关问题