2017-10-26 10 views
0

LINQを使用してネストされたforeachループを簡略化したいが、方法を理解できなかった。私はラムダを使用してSelectManyを使用することはできますが、わからないと思います。この入れ子になった反復の後、ClassAのオブジェクトのリストを作成したいと思います。すべてのヘルプは高く評価されていますマルチレベル辞書のLINQにネストされたforeach

public List<ClassA> GetLists(Dictionary<string, Dictionary<IEnumerable, Dictionary<string, ClassB>>> groups) 
{ 
    var retOutput = new List<ClassA>(); 

    foreach (KeyValuePair<string, Dictionary<IEnumerable, Dictionary<string, ClassB>>> group1 in groups) 
    { 
     foreach (KeyValuePair<IEnumerable, Dictionary<string, ClassB>> group2 in group1.Value) 
     { 
      foreach (KeyValuePair<string, ClassB> group3 in group2.Value) 
      { 
       GetList(retOutput, group1.Key, 
        group2.Key, 
        group3); 
      } 
     } 
    } 

    return retOutput; 
} 

private static void GetList(List<ClassA> retOutput, 
    string group1Key, 
    IEnumerable group2Key, 
    KeyValuePair<string, ClassB> group3) 
{ 
    List<List<string>> itemIdsLists = group3.Value.ItemId.IntoChunks(2000); 
    foreach (var itemIdList in itemIdsLists) 
    { 
     var currentRequest = new ClassA 
     { 
      TransactionType = group1Key, 
      Filters = new Dictionary<string, object>(), 
      ItemIds = new List<string>(), 
      PropStreamsDict = new Dictionary<string, Tuple<long, string>>() 
     }; 
     if (group2Key is Dictionary<string, object>) 
     { 
      currentRequest.Filters = (Dictionary<string, object>)group2Key; 
     } 
     currentRequest.PropStreamsDict.Add(group3.Key, Tuple.Create(group3.Value.StreamId, 
      group3.Value.Uom)); 
     currentRequest.ItemIds.AddRange(itemIdList); 
     retOutput.Add(currentRequest); 
    } 
} 
+0

私は本当に質問を理解していない、あなたの問題はどのようにオブジェクトにLinQを使用することですか? – Ferus7

+0

質問です。最初の方法でこれらのネストされたforeachループを避けるために、より良い方法がありますか(LINQを使用している可能性があります)? – Abhay

+0

ああ、そうだと思いますが、Linqを使って多くの方法を単純化することができます – Ferus7

答えて

2

あなたはforeachネストされた作るためにSelectManyを使用する必要があります。ここで

私が思い付くものを:

public List<ClassA> GetLists(Dictionary<string, Dictionary<IEnumerable, Dictionary<string, ClassB>>> groups) 
{ 
    return groups 
     .SelectMany(grp1 => grp1.Value 
      .SelectMany(grp2 => grp2.Value 
       .SelectMany(grp3 => grp3.Value.ItemId 
        .IntoChunks(2000) 
        .Select(itemIdList => 
         new ClassA 
         { 
          TransactionType = grp1.Key, 
          Filters = grp2.Key is Dictionary<string, object> ? 
           (Dictionary<string, object>)grp2.Key : 
           new Dictionary<string, object>(), 
          ItemIds = new List<string>(itemIdList), 
          PropStreamsDict = new Dictionary<string, Tuple<long, string>> 
          { 
           { grp3.Key, Tuple.Create(grp3.Value.StreamId, grp3.Value.Uom) } 
          } 
         } 
        ) 
       ) 
      ) 
     ) 
     .ToList(); 
} 

あなたのClassAClassBを投稿していなかったので、私は推測しなければなりませんでした。

関連する問題