使用扩展方法按上下文分组筛选查询

时间:2014-10-08 08:56:57

标签: c# vb.net linq

假设我有以下问题:

From row In DataSet.A
Where row.Position <> 5
Group row By row.Name Into eGroup = Group
Select New With {
    .Name = Name,
    .Amount = eGroup.Count(Function(x) x.Money)
}

DataSet有一个字段(Date)。由于分组,在分组之后该字段不再存在。因此,如果我想按日期过滤,我必须在分组之前执行此操作。

我有一个看起来像的列表:

Dim j as New List(of Integer)
j.Add(1)
j.Add(2)

现在我想按月过滤。我知道我可以使用

.Where(Function(el) ls.Contains(datepart(month,el.date)))

但如果我将其设置在Where row.Position <> 5后面,那么查询就不会再运行了,因为它就像破坏了一样,无法连接到代码后面。

任何人都可以告诉我如何设置过滤器?

1 个答案:

答案 0 :(得分:0)

为什么你不能这样做:

Dim months = {1, 2}
Dim query = From row In DataSet.A
            Where row.Position <> 5 AndAlso months.Contains(row.Date.Month)
            Group row By name Into eGroup = Group
            Select New With {
                Key .Name = name,
                .Amount = eGroup.Count(Function(row) row.Field(Of Decimal)("Money"))
            }