这是我的疑问:
rows.GroupBy(row => new TaxGroupObject
{
EnvelopeID = row.Field<int>("EnvelopeID"),
PolicyNumber = row.Field<string>("PolicyNumber"),
TZ = row.Field<string>("TZ")
})
.Select(row =>
{
int i;
if (row.Key.EnvelopeID == 5713 && row.Key.PolicyNumber == "50002617" && row.Key.TZ == "50002617")
i=1+1;
var newRow = structure.NewRow();
newRow["PolicyNumber"]=row.Key.PolicyNumber;
newRow["TZ"]=row.Key.TZ;
newRow["CreditPremiaTaxParagraph45"] = row.Sum(x => decimal.Parse(x["CreditPremiaTaxParagraph45"].ToString()));
newRow["WorklossTax"] = row.Sum(x => decimal.Parse(x["WorklossTax"].ToString()));
newRow["MiscTax"] = row.Sum(x => decimal.Parse(x["MiscTax"].ToString()));
newRow["EnvelopeID"] = row.Key.EnvelopeID;
return newRow;
}
);
internal class TaxGroupObject
{
public long? EnvelopeID{ get; set; }
public string PolicyNumber { get; set; }
public string TZ { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我在"i = 1 + 1"的行上设置断点,在if条件下将我用于该组的所有键与一些硬编码值进行比较.该断点被击中两次,尽管该组假设将所有行与相同的键组合在一起.问题是,对于表中的大多数值,分组工作得很好,我无法理解它是如何可能的.如果您能以任何方式提供帮助,我们将非常感激.
问题是TaxGroupObject没有实现GetHashCode和Equals.这些方法用于GroupBy确定使一个TaxGroupObject对象与另一个对象相等的原因.默认情况下,它是引用相等,而不是属性相等.
这应该工作,使用GetHashCode从算法什么是一个重写System.Object.GetHashCode最好的算法?:
internal class TaxGroupObject
{
public long? EnvelopeID { get; set; }
public string PolicyNumber { get; set; }
public string TZ { get; set; }
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
hash = hash * 23 + EnvelopeID.GetHashCode();
hash = hash * 23 + (PolicyNumber != null ? PolicyNumber.GetHashCode() : -2);
hash = hash * 23 + (TZ != null ? TZ.GetHashCode() : -1);
return hash;
}
}
public override bool Equals(object obj)
{
if (obj.GetType() != typeof(TaxGroupObject))
return false;
var other = (TaxGroupObject)obj;
return this.EnvelopeID == other.EnvelopeID &&
this.PolicyNumber == other.PolicyNumber &&
this.TZ == other.TZ;
}
}
Run Code Online (Sandbox Code Playgroud)
此外,您应该只在分组或字典之类的东西中使用不可变对象.至少,您必须确保此处的对象在分组期间不会更改.