我有一次简化一个循环,如下所示:
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<EventGroupIDLayerTuple, Decimal> BcEventGroupLayerLosses
使用以下玉秀李的回答,我能够这样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());
两者产生相同的结果。
授予既不是特别可读,这是一个良好的实验。 谢谢大家对你的帮助!