0

Type Class:

public partial class URS_Types
{
    [Key]
    public int ID { get; set; }

    public string TypeName { get; set; }

    public int? ParentID { get; set; }
}

I am trying to make a submethod that will receive the ID of "type" of request, it will then get it's parent (using the parentID), then that will get it's parents, until there isn't other category.

I have tried the below, but obviously this only returns the first type due to the select command, however not sure how to tell it to select all the types.

var types = GetURS_Types();

var test = from type in types
           where type.ID == id
           join type2 in types
           on type.ParentID equals type2.ID
           join type3 in types
           on type2.ParentID equals type3.ID
           select type.TypeName;
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100

1 Answers1

0

Lets say you have a have a list of object URS_Types, with the object having ParentID = 0 being the true parent element.

URS_Types parentParent = new URS_Types();
parentParent.ID = 1;
parentParent.ParentID = 0;
parentParent.TypeName= "parentParent";

URS_Types parent = new URS_Types();
parent.ID = 2;
parent.ParentID = 1;
parent.TypeName = "parent";

URS_Types child = new URS_Types();
child.ID = 3;
child.ParentID = 2;
child.TypeName = "child";

URS_Types noParentType = new URS_Types();
noParentType.ID = 4;
noParentType.ParentID = 0;
noParentType.TypeName = "No parent";

List<URS_Types> listType = new List<URS_Types>();
listType.Add(parentParent);
listType.Add(parent);
listType.Add(child);
listType.Add(noParentType);
listType = listType.OrderBy(a => rng.Next()).ToList();

with your function GetURS_Types() it return and ID of 3 (meaning it's the child object). We can make a small while loop to retrieve the true parent of this object.

var childId = GetURS_Types(child); // will return an int: 3
int trueParent = childId; 
URS_Types theTrueParent;
while (trueParent > 0)
{
    theTrueParent = listType.First(x => x.ID == trueParent);
    trueParent = listType.First(x => x.ID == trueParent).ParentID;
}

Note: We will never get the object noParentType (unless we ask GetURS_Types() for it's ID), because we work our way up the list following the ParentID property.

Nathan
  • 83
  • 5