我有一个循环,一旦简化,看起来像这样:

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查询(例如,使用GroupBySumToDictionary)复制此结果? (如对先前问题this的回答Concise way to do a plus equals operation on a Dictionary element that might not be initialized中所建议)



结果

//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());


两者都产生了相同的结果。

授予两者都不是特别可读,这是一个很好的实验。谢谢大家的帮助!

最佳答案

Dictionary<Tuple<A, G>, decimal> dictionary =
            (from a in collectionA
             from b in collectionB
             group (decimal)Func(a, b) by Tuple.Create<A, G>(a, b.groupBy))
            .ToDictionary(g => g.Key, g => g.Sum());

用声明性语法
var dictionary = collectionA
    .SelectMany(a => collectionB,
                (a, b) => new { a, b })
    .GroupBy(g => Tuple.Create(g.a, g.b.groupBy),
             g => Func(g.a, g.b))
    .ToDictionary(g => g.Key, g => g.Sum());

10-01 22:00