我已經寫了的GroupBy聲明,如下所示:的GroupBy與複雜類型的多個屬性
var aggregated = sitesWithLive
.GroupBy(s => new {s.SiteRefNum, s.SiteRefName, s.Address})
.Select(g =>
new Site
{
SiteRefNum = g.Key.SiteRefNum,
SiteRefName = g.Key.SiteRefName,
Address = g.Key.Address,
ContractLive = g.Max(x => x.ContractLive)
});
在組是Address
這是一個複雜類型:
public class Address
{
public string Name { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string Line4 { get; set; }
public string PostCode { get; set; }
public bool IsEmpty()
{
return GetType().GetProperties()
.Where(a => a.GetValue(this) is string)
.Select(a => (string)a.GetValue(this))
.All(string.IsNullOrEmpty);
}
public override string ToString()
{
var addr = Line1 + "," + Line2 + "," + Line3 + "," + Line4 + "," + PostCode;
var address = Regex.Replace(addr, @"^,+|,{2,}|,(?=[\w.])", ", ");
return address;
}
}
然而,這並不正確組通過地址,而不是爲每個元素返回一個單獨的組。
這是我的理解是由複合型組,你必須提供一個IEqualityComparer
所以我創建了以下內容:
public class AddressComparer : IEqualityComparer<Address>
{
public bool Equals(Address x, Address y)
{
return x.ToString() == y.ToString();
}
public int GetHashCode(Address obj)
{
return 1;
}
}
和等提供的不是這樣(的上述子集):
var aggregated = sitesWithLive.GroupBy(s => new {s.SiteRefNum, s.SiteRefName, s.Address}, new AddressComparer())
...
然而,這給我
無法從使用情況推斷類型參數。嘗試明確指定類型參數 。
我對下一步感到不知所措,當然這種分組不應太困難?
Omg,ToString()裏面發生了什麼。爲什麼你需要這裏的正則表達式?從開始建立正確的字符串不是更好嗎?另外,你在GetHashCode中返回1,這是正確的,但效率非常低。 – eocron
@eocron:那真的不是真的要你判斷,真的 - 也許他正在規範來自第三方的一些地址數據?相反,建議一種替代方法來比較對象會更好。 – caesay