locked
How to recursively get the organization AND the parents RRS feed

  • Question

  • User-1188570427 posted

    Is there a way to take this code and pass an organization and then get all of the parents up to the top level where parent organization id is NULL?

            private IEnumerable<OrganizationDTO> GetOrganizationChildrenRecursively(IEnumerable<OrganizationDTO> organizationInfo, int organizationId)
            {
                return organizationInfo
                       .Where(x => x.ParentOrganizationId == organizationId)
                       .Union(organizationInfo.Where(x => x.ParentOrganizationId == organizationId)
                       .SelectMany(y => GetOrganizationChildrenRecursively(organizationInfo, y.OrganizationId)));
            }

    Tuesday, October 2, 2018 7:59 PM

Answers

  • User1724605321 posted

    Hi tvb2727,

    You could find the codes sample in this thread .

    For example , i have model like :

        public class Records
        {
    
            public int id { get; set; }
    
            public string name { get; set; }
    
            public string parent_id { get; set; }
        }

    And the records in database:

    Add the function :

     private IEnumerable<Records> FindAllParents(List<Records> all_data, Records child)
            {
                var parent = all_data.FirstOrDefault(x => x.id.ToString() == child.parent_id);
    
                if (parent == null)
                    return Enumerable.Empty<Records>();
    
                return new[] { parent }.Concat(FindAllParents(all_data, parent));
            }

    Then get the current records and his parent records by :

    var child = db.Records.First(x => x.id == id);
    
    var parents = FindAllParents(db.Records.ToList(), child).ToList();

    Please modify the code samples based on your requirement .

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 3, 2018 5:53 AM