转换为双循环到LINQ查询(Convert double for-loop into a linq

2019-09-21 03:14发布

我有一次简化一个循环,如下所示:

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例如)? (如在提出这个回答上一个问题: 简洁的方式做一个加等于可能不被初始化字典元素上操作 )


结果

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

两者产生相同的结果。

授予既不是特别可读,这是一个良好的实验。 谢谢大家对你的帮助!

Answer 1:

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

在声明synatax

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


Answer 2:

我怀疑你想要的线沿线的东西:

                         // Extract the key/value pair from the nested loop
var result = collectionA.SelectMany(a => collectionB, 
                                    (a, b) => new { 
                                        Key = Tuple.Create(a, (G)b.groupBy),
                                        Value = (decimal) Func(a, b)
                                    })
                        // Group by the key, and convert each group's values
                        // to its sum
                        .GroupBy(pair => pair.Key, 
                                 pair => pair.Value,
                                 (key, values) => new { Key = key,
                                                        Value = values.Sum() })
                        // Make a dictionary from the key/value pairs
                        .ToDictionary(pair => pair.Key, pair => pair.Value);

这是把我的头顶部,并可能需要一些:)我没有及时补充说明的是,但​​所以后来可以做更多的括号。



文章来源: Convert double for-loop into a linq query