這是我正在嘗試做的。我使用LINQ to XML來查詢XML文件,它給了我一個IEnumerable對象,其中T是我的「Village」類,充滿了此查詢的結果。有些結果是重複的,所以我想了IEnumerable對象上執行一個獨特的(),像這樣:C#區別於IEnumerable <T>與自定義IEqualityComparer
public IEnumerable<Village> GetAllAlliances()
{
try
{
IEnumerable<Village> alliances =
from alliance in xmlDoc.Elements("Village")
where alliance.Element("AllianceName").Value != String.Empty
orderby alliance.Element("AllianceName").Value
select new Village
{
AllianceName = alliance.Element("AllianceName").Value
};
// TODO: make it work...
return alliances.Distinct(new AllianceComparer());
}
catch (Exception ex)
{
throw new Exception("GetAllAlliances", ex);
}
}
由於默認的比較不會爲該村對象的工作,我實現了一個自定義的,因爲看到在這裏AllianceComparer類:
public class AllianceComparer : IEqualityComparer<Village>
{
#region IEqualityComparer<Village> Members
bool IEqualityComparer<Village>.Equals(Village x, Village y)
{
// Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y))
return true;
// Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.AllianceName == y.AllianceName;
}
int IEqualityComparer<Village>.GetHashCode(Village obj)
{
return obj.GetHashCode();
}
#endregion
}
鮮明的()方法是行不通的,因爲我有相同數量的帶或不帶它的結果。另一件事,我不知道這是否通常是可能的,但我無法進入AllianceComparer.Equals()查看可能存在的問題。
我在互聯網上發現了這個例子,但我似乎無法讓我的實現工作。
希望有人在這裏可能會看到這裏可能是錯的! 在此先感謝!
您的catch/throw構造使調用函數無法再選擇捕獲(ArgumentException)或catch(IOException)(示例)。對於這種情況,您可能最好將try/catch一起移除 - 此外,方法的名稱將成爲異常StackTrace屬性的一部分。 – 2009-12-16 20:22:59