LINQ过滤条件

时间:2015-09-08 06:05:18

标签: sql vb.net linq

我有两张桌子:

People (~10000 Record)
PID Primary Key

PeopleCharater (~500000 Record)
OID Primary Key
PID Foreign Key
RecordDate(DateTime of the record is created)

它是一对多的关系,一个PID有多个OID。

我想选择一个与Hashset(Of PID)匹配的OID列表以及StartDate和EndDate之间的RecordDate 棘手的部分是,应该包括< = StartDate的最大RecordDate。

示例:

PeopleCharacter
OID PID RecordDate
a   1   2014-10-09
b   1   2015-12-10
c   1   2015-12-15
d   1   2016-02-25

如果StartDate为2015-01-01至2015-12-31,则检索到的记录应为b和c。

如何编写LINQ查询以检索记录?

我当前的代码:

Dim PIDHash as Hashset(Of PID)(~10000 PID)
db.Filter(Function(x) x.RecordDate >= StartDate andalso x.RecordDate <= EndDate andalso PIDHash.contains(x.PID)).
   Union(??? another filter to select the greatest RecordDate < StartDate)

由于性能问题,必须限制从数据库检索的次数。存储过程解决方案被接受。

2 个答案:

答案 0 :(得分:0)

在C#中它将是:

var query=db.PeopleCharacter
  .Where(p=>PIDHash.Contains(p.PID));
var results=query
  .Where(p=>p.RecordDate>=StartDate && p.RecordDate<=EndDate)
  .Union(
    query.Where(p=>p.RecordDate<StartDate)
      .OrderByDescending(p=>p.RecordDate)
      .Take(1)
  );

使用VB.NET的在线转换器给出:

Dim query = db.PeopleCharacter.Where(Function(p) PIDHash.Contains(p.PID))
Dim results = query.Where(Function(p) p.RecordDate >= StartDate AndAlso p.RecordDate <= EndDate).Union(query.Where(Function(p) p.RecordDate < StartDate).OrderByDescending(Function(p) p.RecordDate).Take(1))

答案 1 :(得分:0)

最后在我的大四学生的帮助下弄清楚。

Dim query = db.PeopleCharacter.Where(Function(p) PIDHash.Contains(p.PID))
Dim RecordDateQuery = query.Where(Function(y) y.RecordDate <= StartDate).
                            GroupBy(Function(x) x.PID).
                            Select(Function(f) New With {.PID = f.key, .RecordDate = f.Max(Function(t) t.RecordDate)})
Dim results = query.Where(Function(p) p.RecordDate >= StartDate AndAlso p.RecordDate <= EndDate).
                  Union(query.Join(RecordDateQuery,
                                   Function(x) New With {.PID = x.PID, .RecordDate = x.RecordDate},
                                   Function(y) New With {.PID = y.PID, .RecordDate = y.RecordDate},
                                   Function(x, y) x))