我認爲你需要使用的SelectMany
此重載:
http://msdn.microsoft.com/en-us/library/bb534631(v=vs.110).aspx
但我也認爲你需要兩次調用它。鑑於以下結構,我想出了以下幾點:
class Program
{
static void Main(string[] args)
{
var groups = new List<Group>();
var items = groups
.SelectMany(group => group.SubGroups, (group, subGroup) => new
{
group,
subGroup
})
.SelectMany(anon => anon.subGroup.Items, (anon, item) => new
{
Group = anon.group,
SubGroup = anon.subGroup,
Item = item
});
Console.Read();
}
}
class Group
{
public string GroupName { get; set; }
public List<SubGroup> SubGroups { get; set; }
}
class SubGroup
{
public string SubGroupName { get; set; }
public List<Item> Items { get; set; }
}
class Item
{
public string ItemName { get; set; }
}
基本上,你項目轉發,以保持對父項的引用。在您的具體結構,它應該是這樣的:
var items = groups
.SelectMany(group => group.SubGroups, (group, subGroup) => new
{
group,
subGroup
})
.SelectMany(anon => anon.subGroup.Items, (anon, item) => new
{
anon.group.MainGroupId,
anon.subGroup.SubGroupId,
item.ItemMpId
});
這給你匿名類型的大名單目前沒有經過過濾,如果你要過濾的東西,你去簡單地追加一個Where
呼叫到Items
合併:
var items = groups
.SelectMany(group => group.SubGroups, (group, subGroup) => new
{
group,
subGroup
})
.SelectMany(anon => anon.subGroup.Items.Where(item => item.ItemMpId == work.ItemMpId), (anon, item) => new
{
anon.group.MainGroupId,
anon.subGroup.SubGroupId,
item.ItemMpId
});
這應該解決您的SelectMany
使用的要求,但是,我不相信這是完全可讀。
如果你有自己的想法,併發布你的嘗試,我們可以幫助你解決任何代碼問題。 – Baldrick