LINQ选择Max为一列而Disting为另一列的行

时间:2013-12-05 16:46:45

标签: c# vb.net linq linq-to-entities

我正在使用LINQ to Entities来查询以下MS-SQL表:

RateID  RateTypeID  Amount  EffectiveDate   IsRetired
------  ----------  ------  -------------   ---------
1       1           0.565   1/1/2013 0:00   FALSE
2       2           6.000   1/1/2013 0:00   FALSE
3       3           9.000   1/1/2013 0:00   FALSE
4       4           12.000  1/1/2013 0:00   FALSE
5       5           1.500   1/1/2013 0:00   FALSE
6       1           0.550   7/1/2012 0:00   FALSE
7       1           0.495   1/1/2012 0:00   FALSE
8       3           8.000   1/1/2011 0:00   FALSE
9       3           11.000  1/1/2015 0:00   FALSE
10      5           2.000   7/1/2013 0:00   TRUE

我想构建一个函数,它将使用LINQ返回IQueryable(Of Rate),我可以将其加入其他查询,以便RateTypeID有效地确定应用于每个项目的当前速率。 IsRetired必须为false,我需要最近的EffectiveDate行。

这是我得到的最接近的(LINQPad VB语句):

Dim dateNow As Date = Date.Now
Dim result = (
    From r In Rates
    Where r.IsRetired = False And r.EffectiveDate <= dateNow
    Group r By r.RateTypeID
    Into rg = Group
    Select New With {
        .cr = rg.OrderByDescending(Function(r) r.EffectiveDate).Take(1)
    }
)
result.Dump()

此查询返回DbQuery(Of AnonymousType_1(Of IEnumerable(Of Rate)))(每个包含1个费率项的集合集合),这不是我想要的。

这个Q&amp; A解决了一个非常类似的问题但是在SQL而不是LINQ中: How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

我在vb.net编码,但也会接受c#答案。谢谢!

1 个答案:

答案 0 :(得分:6)

使用Take()返回IEnumerable<T>FirstOrDefault()只返回<T>,所以:

IQueryable<RecentRate> query = from r in Rates
                               where r.IsRetired == false && r.EffectiveDate <= dateNow
                               group r by r.RateTypeID into rg
                               select new RecentRate
                               {
                                 Rate = rg.OrderByDescending(r => r.EffectiveDate).FirstOrDefault()
                               };

这可能有效:

   IQueryable<Rate> query = from r in Rates
                            where r.IsRetired == false && r.EffectiveDate <= dateNow
                            group r by r.RateTypeID into rg
                            select rg.OrderByDescending(r => r.EffectiveDate).FirstOrDefault();

我认为这是VB语法

Dim result = (
    From r In Rates
    Where r.IsRetired = False And r.EffectiveDate <= dateNow
    Group r By r.RateTypeID
    Into rg = Group
    Select rg.OrderByDescending(Function(r) r.EffectiveDate).FirstOrDefault()
)