1

我在使用简单的 linq 查询时遇到问题。

例如,我有一个包含两列的 MS sql 表。姓名和日期

在这个表中大约有 3 行。

行的示例

Name          Date
SalesReport   10/1/2013
SalesReport   10/2/2013
Tax Report    10/2/2013

我希望我的 linq 查询按“名称”分组,但按日期排序,因此分组字段具有最新日期,我的结果看起来像

Name          Date
SalesReport   10/2/2013
TaxReport     10/2/2013

这是我正在使用的代码,但它不会正确排序。无论我更改升序或降序属性,我总是得到相同的日期。

Dim List = From w In db.reports
                Order By w.Date Descending
                Group By Name = w.Name Into g = Group
                Select g
4

1 回答 1

2

The main problem you have is that you're not actually grouping your data by maximum date properly. All your current Order By is doing is ordering the data as it goes in to the grouping, not on the way out.

What you need to do is manipulate the data with a grouping, and return the name and the maximum date (as you would with a SQL GROUP BY clause):

Dim List = From w In db.reports
            Group w By Name = w.Name Into g = Group
            Select Name = Name, [Date] = g.Max(Function(p) p.Date)
            Order By Name
于 2013-10-09T22:21:52.343 回答