我已经为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)));
}
最佳答案
LINQ的Enumerable.Sum(...)
方法在checked
块内执行添加。这意味着如果总和溢出,他们会故意抛出异常。
您的总和不在checked
块内,因此它是否引发异常取决于...是从checked
块内部调用还是我相信的程序集属性。
关于c# - LINQ Sum OverflowException?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11033777/