我有一个循环,一旦简化,它看起来像这样:
Dictionary<Tuple<A,G>,Decimal> results = new Dictionary<Tuple<A,G>,Decimal>();
foreach( A a in collectionA )
foreach( B b in collectionB )
results [Tuple.Create(a, (G)b.groupBy)] += (Decimal) Func(a, b);
有没有办法可以使用 Linq 查询(例如GroupBy
,使用Sum
和)复制此结果?ToDictionary
(正如对上一个问题的回答中所建议的:在可能未初始化的 Dictionary 元素上执行加号等于操作的简洁方法)
结果
//Dictionary<EventGroupIDLayerTuple, Decimal> BcEventGroupLayerLosses
使用以下 Yuxiu Li 的回答,我能够从链接的问题转换这 4 班轮:
BcEventGroupLayerLosses = new Dictionary<EventGroupIDLayerTuple, Decimal>();
foreach( UWBCEvent evt in this.BcEvents.IncludedEvents )
foreach( Layer lyr in this.ProgramLayers )
BcEventGroupLayerLosses.AddOrUpdate(
new EventGroupIDLayerTuple(evt.EventGroupID, lyr),
GetEL(evt.AsIfs, lyr.LimitInMillions, lyr.AttachmentInMillions),
(a, b) => a + b);
进入这一个班轮:
BcEventGroupLayerLosses = this.BcEvents.IncludedEvents
.SelectMany(evt => ProgramLayers, (evt, lyr) => new { evt, lyr })
.GroupBy(g => new EventGroupIDLayerTuple(g.evt.EventGroupID, g.lyr),
g => GetEL(g.evt.AsIfs, g.lyr.LimitInMillions, g.lyr.AttachmentInMillions))
.ToDictionary(g => g.Key, g => g.Sum());
两者都产生了相同的结果。
当然,两者都不是特别可读,这是一个很好的实验。感谢大家的帮助!