Home > Software design >  How do I make my query return one another property inside dictionary
How do I make my query return one another property inside dictionary

Time:02-08

Below query returns ItemNo's of children and grandchildren in an array of dictionaries, so that relationship is maintained.

    public async Task<List<KeyValuePair<string, IEnumerable<string>>>> GetChild(string parentItemNo)
    {
               var childDetails = await DbContext.Items
                    .Where(x => x.ItemNo== parentItemNo)
                    .SelectMany(x => x.Children.Select(c => new
                    {
                        c.ItemNo, // I can select c.ItemName as well
                        // how do I select ItemName below, tried Select(gc => new { gc.ItemNo, gc.ItemName})
                        GrandChildItemNos = c.Children.Select(gc => gc.ItemNo)  
                    })).ToListAsync();

                var dictionary = childDetails.ToDictionary(d => d.ItemNo, d => d.GrandChildItemNos).ToList();  // how do i set ItemName here

                return dictionary;
       
    }

Query returns children(key) and grandchild(value), like below

 [{"Key":"A","Value":["AQ11", AH45]},{"Key":"C","Value":["CN22", "CL33", "CG24"]}]

how do I to return 'ItemName' as well for each children and grandchildren.

CodePudding user response:

You should write:

public async Task<List<Child>> GetChild(string parentItemNo)
{
               return await DbContext.Items
                    .Where(x => x.ItemNo== parentItemNo)
                    .SelectMany(x => x.Children.Select(c => new Child
                        {
                            ItemNo = c.ItemNo,
                            ItemName = c.ItemName,
                            GrandChildItemNos = c.Children.Select(gc => 
                               new GrandChild 
                               { 
                                  ItemNo = gc.ItemNo, 
                                  ItemName = gc.ItemName 
                               })  
                        })).ToListAsync();
       
 }

Using this class

public class GrandChild
{
    public string ItemNo {get;set;}
    public strng ItemName {get;set;}
}

public class Child
{
    public string ItemNo {get;set;}
    public string ItemName {get;set;}
    public IEnumerable<GrandChild> GrandChildItemNos {get;set;}
}
  •  Tags:  
  • Related