3

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

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

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

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

4

2 回答 2

4
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());
于 2012-08-10T17:20:02.070 回答
1

我怀疑您想要以下内容:

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

这不是我的想法,可能需要更多的括号:) 我还没有时间添加解释,但可以稍后再添加。

于 2012-08-10T17:09:06.990 回答