问题描述
免责声明::自两天以来,我一直在与这个问题作斗争(我在SO上读过很多类似的问题).通过Linq并寻求帮助.
Disclaimer: I've been fighting against this problem since 2 days (I've read a lot of similar questions on SO).. so be patient, I'm missing something about the Group By with Linq and asking for help.
我有一个Macrotab
的列表.每个Macrotab
对象都包含一个Tab
列表.每个Tab
对象都在内部,而Slot
在里面.
I have a list of Macrotab
. Each Macrotab
object contains a list of Tab
.Each Tab
object inside with Slot
inside.
List<MacroTab> hierarchaldata = CreateHierarchaldata();
*为了使问题易于阅读,我将填充一组示例数据的CreateHierarchaldata移到了.NetFiddle中: https://dotnetfiddle.net/8mF1qI
*For keeping the question easy to read I've moved the CreateHierarchaldata, which populates a set of sample data, to .NetFiddle: https://dotnetfiddle.net/8mF1qI
以下几行使用Linq 展平此结构:
The following lines flattens this structure using Linq:
var flattenedList = (from macroTab in hierarchaldata
from tab in macroTab.Tabs
from slot in tab.Slots
select new {macroTab.IDMacroTab, tab.IDTab, slot.IDSlot}).ToList();
将数据聚合回层次结构
我尝试使用Linq Group By
回到原始列表.这是我的目标:汇总MacroTab,Tab和Slot的ID的数据并重新创建原始列表,但是它没有按预期工作**:
Aggregate the data back to hierarchy
I've tried to get back to the original list using the the Linq Group By
. This was my objective: to Aggregate the data for the Id of the MacroTab, Tabs and Slots and recreate the original list, but it doesn't work as expected**:
var antiflatten = from macrotab in flattenedList
group macrotab by new {macrotab.IDMacroTab}
into macrotabs
let macrotabFirst = macrotabs.First()
select new MacroTab
{
IDMacroTab = macrotabFirst.IDMacroTab,
Tabs = (from macrotab in macrotabs
group macrotabs by new {macrotab.IDTab}
into tabs
let tabFirst = tabs.First()
select new Tab(){ HelperClass = tabFirst}).ToList()
};
**属性HelperClass仅用于调试目的,希望它不会引起混淆,我将其留给解释了Visual Studio调试器的屏幕截图
**The property HelperClass is just for debugging purpose, I hope it's not confusing, I've left it to explain the Visual Studio debugger's screenshot
推荐答案
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();
这篇关于Linq:从扁平化列表重建层次结构数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!