如何在字典中使我的查询 return 彼此 属性

How do I make my query return one another property inside dictionary

下面查询字典数组中子孙的returns个ItemNo,这样就保持了关系。

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

查询returns children(key) and grandchild(value),如下所示

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

我如何return'ItemName'以及每个子孙

你应该写:

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

使用这个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;}
}