2013-12-09 1 views
-1

그룹 -> 하위 그룹 -> 항목 형식으로 정렬 된 계층 적 데이터가 있습니다. 내가 C# 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 쿼리를 사용하는 방법을 가르쳐주세요 SelectMany

사용하여 일부 효율적으로 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; } 
} 

는 기본적으로, 상위 항목에 대한 참조를 유지하기 위해 앞으로 전망이다. 특정 구조에서, 그 결과는 다음과 같습니다 당신이 단순히 Items 병합에 Where 전화를 추가 가서 물건을 필터링 할 경우

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

이 당신에게 현재 필터링되지 익명 형식의 큰 목록을 제공합니다 :

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

관련 문제