2013-12-09 28 views
-1

我有一個分層數據排列在組 - >子組 - >項目。 我想用的SelectManyC#LINQ查詢從不同級別的層次中選擇數據

IEnumerable<MainGroup> res = <somedata containg hierarchy Groups -> SubGroups -> Items> ; 
foreach (var group in res) 
{ 
    foreach (var subgroup in group.SubGroups) 
    { 
     foreach (var item in subgroup.ItemMps) 
     { 
      if (item.ItemMpId.ToString() == work.ItemMpID) 
      { 
       temp = temp + group.MainGroupId + "," + subgroup.SubGroupId + "," + 
         item.ItemMpId + "-|-"; 
      } 
     } 
    } 
} 

請有人告訴我,我怎麼可以在這裏使用LINQ查詢到下面這段代碼轉換成一些有效的LINQ查詢。請注意我的要求是使用SelectMany,並且我的最終輸出需要具有來自所有層次結構級別的不同屬性。

+0

如果你有自己的想法,併發布你的嘗試,我們可以幫助你解決任何代碼問題。 – Baldrick

回答

1

我認爲你需要使用的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使用的要求,但是,我不相信這是完全可讀。

+0

坦克很多。這正是我想要的。 – user3056239