EventLogEntry のカスタム IEqualityComparer を実装しました。
public class EventLogEntryListComparison :
IEqualityComparer<List<EventLogEntry>>,
IEqualityComparer<EventLogEntry>
の場合IEqualityComparer<List<EventLogEntry>>
、GetHashCode 関数は非常に単純です。
public int GetHashCode(List<EventLogEntry> obj)
{
return obj.Sum(entry => 23 * GetHashCode(entry));
}
ただし、これにより、特定のエントリに対して OverflowException がスローされます。
"Arithmetic operation resulted in an overflow."
at System.Linq.Enumerable.Sum(IEnumerable`1 source)
at System.Linq.Enumerable.Sum[TSource](IEnumerable`1 source, Func`2 selector)
at <snip>.Diagnostics.EventLogAnalysis.EventLogEntryListComparison.GetHashCode(List`1 obj) in C:\dev\<snip>Diagnostics.EventLogAnalysis\EventLogEntryListComparison.cs:line 112
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
at <snip>.Diagnostics.EventLogAnalysis.Program.AnalyseMachine(String validMachineName) in C:\dev\<snip>.Diagnostics.EventLogAnalysis\Program.cs:line 104
at System.Threading.Tasks.Parallel.<>c__DisplayClass2d`2.<ForEachWorker>b__23(Int32 i)
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
デバッグ中に同じエラーを取得しようとして、すぐにウィンドウに表示できなかった後、コードをこれに変更し、さようならOverflowException?
int total = 0;
foreach (var eventLogEntry in obj)
{
total += GetHashCode(eventLogEntry);
}
return total;
LINQ の Sum 関数の動作が異なるのはなぜですか?
編集 2
いくつかのコメントのおかげで、修正された目的の GetHashCode 関数は次のようになりました。
public int GetHashCode(List<EventLogEntry> obj)
{
return unchecked(obj.Aggregate(17,
(accumulate, entry) =>
accumulate * 23 + GetHashCode(entry)));
}