単純化すると、次のようなループがあります。
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要素に対してplus equals操作を実行する簡潔な方法)
結果
//Dictionary<EventGroupIDLayerTuple, Decimal> BcEventGroupLayerLosses
以下のYuxiuLiの回答を使用して、リンクされた質問からこの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());
そして、どちらも同じ結果をもたらしました。
どちらも特に読みやすいとは言え、これは良い実験でした。皆さんの助けに感謝します!