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クエリを使用してこの結果を複製する方法はありますか(たとえばGroupBySumを使用)?(前の質問に対するこの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());

そして、どちらも同じ結果をもたらしました。

どちらも特に読みやすいとは言え、これは良い実験でした。皆さんの助けに感謝します!

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 に答える