将双for循环转换为linq查询

时间:2012-08-10 16:57:09

标签: c# linq .net-4.0 dictionary

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

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

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

虽然没有特别可读,但这是一个很好的实验。谢谢大家的帮助!

2 个答案:

答案 0 :(得分: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());

答案 1 :(得分: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);

这是我的头脑,可能需要更多括号:)我没有时间添加解释,但稍后可以这样做。