在多级字典中嵌套到LINQ的foreach

时间:2017-10-26 05:27:47

标签: c# linq

我想使用LINQ简化嵌套的foreach循环,但无法弄清楚方法。我想我可以使用lambda使用SelectMany但不确定。我希望在此嵌套迭代后创建ClassA的对象列表。任何帮助表示赞赏:

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

1 个答案:

答案 0 :(得分:2)

您应该使用SelectMany来嵌套foreach

我想出的是:

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所以我不得不猜测。