VB.Net中具有多个属性的LINQ Group by
我在这个问题上花了很多时间。我可以做简单的分组LINQ查询(在一个属性上),但对于多个字段,我有点卡住了。。。 以下是我想做的LINQPad示例:VB.Net中具有多个属性的LINQ Group by,vb.net,linq,list,group-by,Vb.net,Linq,List,Group By,我在这个问题上花了很多时间。我可以做简单的分组LINQ查询(在一个属性上),但对于多个字段,我有点卡住了。。。 以下是我想做的LINQPad示例: dim lFinal={new with {.Year=2010, .Month=6, .Value1=0, .Value2=0}, new with {.Year=2010, .Month=6, .Value1=2, .Value2=1}, new with {.Year=2010, .Month=
dim lFinal={new with {.Year=2010, .Month=6, .Value1=0, .Value2=0},
new with {.Year=2010, .Month=6, .Value1=2, .Value2=1},
new with {.Year=2010, .Month=7, .Value1=3, .Value2=4},
new with {.Year=2010, .Month=8, .Value1=0, .Value2=1},
new with {.Year=2011, .Month=1, .Value1=2, .Value2=2},
new with {.Year=2011, .Month=1, .Value1=0, .Value2=0}}
Dim lFinal2 = From el In lFinal
Group el By Key = new with {el.Year,el.Month}
Into Group
Select New With {.Year = Key.Year, .Month=Key.Month, .Value1 = Group.Sum(Function(x) x.Value1), .Value2 = Group.Sum(Function(x) x.Value2)}
lFinal.Dump()
lFinal2.Dump()
最终列表有6个项目,我希望lFinal2有4个项目:2010-6和2011-1应该分组
提前感谢。不是100%确定,但group by可能使用Equals()和/或GetHashCode实现,因此在执行隐式创建时:
= Group el By Key = new with {el.Year,el.Month}
隐式对象不知道同时检查年份和月份(仅仅因为它有属性并不意味着它在与其他对象进行比较时检查它们)
因此,您可能需要执行以下操作:
= Group el By Key = new CustomKey() { Year = el.Year, Month = el.Month };
public class CustomKey{
int Year { get; set; }
int Month { get; set; }
public override bool Equals(obj A) {
var key (CustomKey)A;
return key.Year == this.Year && key.Month == this.Month;
}
}
谢谢!
但是我注意到我还需要编写GetHashCode函数来使它工作。我提供了最终类+LINQ GroupBy的VB.Net翻译:
类别:
Public Class YearMonth
Implements IEquatable(Of YearMonth)
Public Property Year As Integer
Public Property Month As Integer
Public Function Equals1(other As YearMonth) As Boolean Implements System.IEquatable(Of YearMonth).Equals
Return other.Year = Me.Year And other.Month = Me.Month
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.Year * 1000 + Me.Month * 100
End Function
End Class
以及LINQ查询:
Dim lFinal2 = From el In lFinal
Group el By Key = New YearMonth With {.Year = el.Year, .Month = el.Month}
Into Group
Select New ItemsByDates With {.Year = Key.Year,
.Month = Key.Month,
.Value1 = Group.Sum(Function(x) x.Value1),
.Value2 = Group.Sum(Function(x) x.Value2)}
使用
键
关键字使匿名类型中的属性不可变,然后它们将用于比较
Dim lFinal2 = From el In lFinal
Group el By Key = new with {key el.Year, key el.Month}
Into Group
Select New With {
.Year = Key.Year,
.Month = Key.Month,
.Value1 = Group.Sum(Function(x) x.Value1),
.Value2 = Group.Sum(Function(x) x.Value2)
}
+1.虽然OP的语法可以很好地与LINQ to SQL配合使用,但在LINQ to对象上使用时,它将生成当前输出。+0虽然这是正确的,但是
键
是正确的答案。+0虽然这是正确的,但是键
是正确的答案。我还必须实现GetHashCode()为了让它工作。