代码之家  ›  专栏  ›  技术社区  ›  Revious

Linq挑战:将这段代码从方法链转换为标准Linq

  •  1
  • Revious  · 技术社区  · 7 年前

    挑战是如何从方法链转换到标准linq,这是一段充满group-by的代码。

    上下文

    Linq: rebuild hierarchical data from the flattened list

    多亏了@Akash Kava,我找到了解决问题的方法。

    链法公式

    var macroTabs = flattenedList
            .GroupBy(x => x.IDMacroTab)
            .Select((x) => new MacroTab
            {
                IDMacroTab = x.Key,
                Tabs = x.GroupBy(t => t.IDTab)
                        .Select(tx => new Tab {
                            IDTab = tx.Key,
                            Slots = tx.Select(s => new Slot {
                               IDSlot = s.IDSlot
                         }).ToList()
                }).ToList()
            }).ToList();
    

    发生的事情与此类似。。

    var antiflatten = flattenedList
        .GroupBy(x => x.IDMacroTab)
        .Select(grouping => new MacroTab
        {
            IDMacroTab = grouping.Key,
            Tabs = (from t in grouping
                    group grouping by t.IDTab
                    into group_tx
                    select new Tab
                    {
                        IDTab = group_tx.Key,
                        Slots = (from s in group_tx
                        from s1 in s    
                        select new Slot
                        {
                            IDSlot = s1.IDSlot
                        }).ToList()
                    }).ToList()
        });
    

    LinqPad中的结果

    enter image description here

    https://dotnetfiddle.net/8mF1qI

    1 回复  |  直到 6 年前
        1
  •  0
  •   Revious    7 年前

    作为 LinqPad 分组依据 List 属于 Groups . Group 只有一处房产 :一个

    enter image description here

    作为 this answer 状态,从IGrouping的定义( IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable )那个 只有 访问子组内容的方法是遍历元素(foreach、groupby、select、ecc)。

    enter image description here

    And here is the source code on Fiddle

    但让我们继续尝试另一种解决方案:

    我们平时做什么 SQL语句 当我们做一个 分组依据 是列出所有列 但是 被分组的那个。 和Linq不同。。它仍然返回所有列。

    enter image description here

    推荐文章