[英]LINQ Select rows with Max of one column and Distinct in another
I am using LINQ to Entities to query the following MS-SQL table: 我正在使用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
I want to build a function that will use LINQ to return an IQueryable(Of Rate)
which I can then join in to other queries to efficiently determine the current rate applied to each item, by RateTypeID
. 我想构建一个函数,该函数将使用LINQ返回IQueryable(Of Rate)
,然后可以将其RateTypeID
到其他查询中,以通过RateTypeID
有效地确定应用于每个项目的当前汇率。 IsRetired
must be false and I need the row with the most recent past EffectiveDate
. IsRetired
必须为false,并且我需要包含最近EffectiveDate
。
Here is the closest I have gotten (LINQPad VB Statements): 这是我最近得到的(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()
This query returns DbQuery(Of AnonymousType_1(Of IEnumerable(Of Rate)))
(a collection of collections each with 1 rate item), which isn't quite what I want. 该查询返回DbQuery(Of AnonymousType_1(Of IEnumerable(Of Rate)))
(每个具有1个费率项的集合的集合),这并不是我想要的。
This Q&A solves a very similar problem but is in SQL instead of LINQ: How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL? 这个问题解答解决了一个非常相似的问题,但是是用SQL而不是LINQ进行的: 我如何通过SQL中的另一列选择具有MAX(Column value),DISTINCT的行?
I am coding in vb.net but would also take ac# answer. 我在vb.net中编码,但也会采用ac#答案。 Thanks! 谢谢!
Using Take()
returns IEnumerable<T>
while FirstOrDefault()
returns just <T>
, so: 使用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()
};
This might work: 这可能起作用:
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();
I think this is the VB syntax 我认为这是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()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.