how to transform the following in C#? - c#

I have the following model
public class Node
{
public int AutoIncrementId { get; set; }
public string Text { get; set; }
public List<Node> Nodes { get; set; }
...//other propeties
}
I want to transform the data into the following model,
public class TreeView
{
public int Id {get; set;}
public string Text {get; set;}
public List<TreeView> Items {get; set;}
}
I started with the following, but then realised how am I going to know when to stop?
the variable test holds the node data
var items = test.Data.Select(x => new TreeViewItemModel
{
Id = x.AutoIncrementId.ToString(),
Text = x.Text,
Items = x.Nodes.Select(y=> new TreeViewItemModel(
{
Id = y.AutoIncrementId.ToString(),
Text = y.Text,
Items = //do I keep going?
}));
}
);

You can use recursion to do that:
public TreeView ConvertToTreeView(Node node)
{
TreeView tv = new TreeView();
tv.Id = node.AutoIncrementId;
tv.Text = node.Text;
if (node.Nodes != null && node.Nodes.Count > 0)
{
tv.Items = new List<TreeView>();
node.Nodes.ForEach(x => tv.Items.Add(ConvertToTreeView(x)));
}
return tv;
}

For clarity and simplicity, this works nicely:
public TreeView ConvertNode(Node rootNode)
{
var tree = new TreeView
{
Id = rootNode.AutoIncrementId,
Text = rootNode.Text,
Items = new List<TreeView>()
};
if (rootNode.Nodes != null)
{
foreach (var node in rootNode.Nodes)
{
tree.Items.Add(ConvertNode(node));
}
}
return tree;
}

I prefer this form.
public TreeView ConvertToTreeView(Node node)
{
return new TreeView
{
Id = node.AutoIncrementId;
Text = node.Text;
Items = node.Nodes.Select(ConvertToTreeView).ToList()
};
}
Edit: Yes Baldrick, I did :P and
public TreeView ConvertToTreeView(Node node)
{
return new TreeView
{
Id = node.AutoIncrementId;
Text = node.Text;
Items = node.Nodes != null
? node.Nodes.Select(ConvertToTreeView).ToList()
: new List<TreeView>()
};
}
Just doesn't look as nice.

Related

How to iterate and sum numeric values stored in children objects to the parent object in a tree-like data

I have a C# object which may parent itself in order to create a tree-like data structure.
public class AssetType
{
public long? Id { get; set; }
public string Definition { get; set; }
public int AssetCount { get; set; }
public long? ParentId { get; set; }
public ICollection<AssetType> Children { get; set; }
}
I succesfully populated the data and I have a collection of root AssetTypeTree objects with children. Now, what I need is to sum the AssetCount value of every children to their parent iteratively. For example my initial data may be as follows:
-ELECTRONICS -> AssetCount: 0
+COMPUTERS -> AssetCount: 0
*PERSONAL COMPUTERS -> AssetCount: 5
*SERVERS -> AssetCount: 3
+PRINTERS -> AssetCount: 2
-FURNITURES -> AssetCount: 0
+TABLES -> AssetCount: 4
Here, the AssetCount values are correct in the leaf nodes. But I need to also populate the values of the parent nodes. Here, COMPUTERS should have a count of 8, ELECTRONICS should be 10 and FURNITURES should be 4. Depth of nodes may differ and also non-leaf nodes may also have a initial count value other than 0.
It should be possible to write a recursive iteration of some sort but I couldn't wrap my head around this really.
Try following :
class Program
{
static void Main(string[] args)
{
AssetType root = new AssetType();
AssetType.AddCount(root);
}
}
public class AssetType
{
public long? Id { get; set; }
public string Definition { get; set; }
public int AssetCount { get; set; }
public long? ParentId { get; set; }
public ICollection<AssetType> Children { get; set; }
public static int AddCount(AssetType parent)
{
foreach (AssetType child in parent.Children)
{
parent.AssetCount += AddCount(child);
}
return parent.AssetCount;
}
}
A recursive function should do the trick nicely. Here is something i typed up real quick. Make sure there is no circular loops, as i did not check for that.
private int GetAssetCount(AssetType asset)
{
var assetCount = 0;
if (asset.Children != null)
{
foreach (var child in asset.Children)
{
child.AssetCount = GetAssetCount(child);
assetCount += child.AssetCount;
}
}
else
{
assetCount = asset.AssetCount;
}
return assetCount;
}
Sanity Check
private void TestAssetRecursion()
{
var asset0 = new AssetType()
{
AssetCount = 0
};
var asset1 = new AssetType()
{
AssetCount = 0
};
var asset2 = new AssetType()
{
AssetCount = 0
};
var asset3 = new AssetType()
{
AssetCount = 3
};
var asset4 = new AssetType()
{
AssetCount = 4
};
asset0.Children = new AssetType[] { asset1 };
asset1.Children = new AssetType[] { asset2 };
asset2.Children = new AssetType[] { asset3, asset4 };
asset0.AssetCount = GetAssetCount(asset0);
}

Tree hierarchy setting flag true if child exists C#

I am trying to set issetting flag to true , if child exists for a
parent.
//Class file
public class EopsModule
{
public int ID { get; set; }
public string ModuleCode { get; set; }
public string Description { get; set; }
public bool IsDefaultModule { get; set; }
public int? ParentID { get; set; }
public bool IsSetting { get; set; }
public List<EopsModule> Children { get; set; }
}
public IResponseResult GetApplicationSettingWithModule()
{
IResponseResult responseResult = new ResponseResult();
dynamic dynamic = new ExpandoObject();
try
{
var settingsDetails = _databaseManager.GetMultipleDataByJson(DatabaseStoredProcedures.spGetAllApplicationSetting.ToString()).Result;
var oObjectDeserializeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(settingsDetails);
//get here all EopsModule in List<EopsModule>
var moduleTreeHierarchy = _eopsModuleManager.GetAllEopsModuleWithHierarchy().Result;
dynamic.settingsDetails = oObjectDeserializeObject;
dynamic.moduleTreeHierarchy = moduleTreeHierarchy;
string oModuleCode = string.Empty;
foreach (var item in oObjectDeserializeObject)
{
oModuleCode = item.moduleCode;
moduleTreeHierarchy.
Where(x => x.ModuleCode == oModuleCode).ToList().ForEach(x =>
{
x.IsSetting = true;
});
}
responseResult = Helper.Response.ResponseModel(dynamic, true, Helper.Constants.ApiSuccess, HttpStatusCode.OK, true);
}
catch (Exception)
{
responseResult = Helper.Response.ResponseModel(null, false, Helper.Constants.ApiFailure, HttpStatusCode.BadRequest, true);
}
return responseResult;
}
The loop i am iterating is working for parent level but , its not updating the value for child values,
wondering if it can be achieved by recursive function.
Please find the output with existing code :
Have you tried something like this? I did not pass it through compiler but you'll get the idea.
public UpdateModuleAndChildren(Module moduleTreeHierarchy) {
if(moduleTreeHierarchy.children != null && moduleTreeHierarchy.children.Count() > 0) {
moduleTreeHierarchy.children.forEach(x => { this.UpdateModuleAndChildren(x) });
module.IsSetting = true;
}
}
Let me know if it helps.
In your code you will just call this.UpdateModuleAndChildren(moduleTreeHierarchy)

Search in hierarchy tree to get tree with only result node

I have hierarchy tree, each element has a list of children and so on.
This is the class:
public class HierarchyItem
{
public int? HierarchyID { get; set; }
public string label { get; set; }
public List<HierarchyItem> children { get; set; }
public int Level { get; set; }
public int ParentID { get; set; }
}
I am trying to search for all the nodes that their label contains my search term.
I already managed to get the nodes that match my search term.
In addition i created a recursion to get all the parents (until the top node) for every node that match my search term.
The problem is that in this way i get a reverse tree:
Every children has parent that has parent and so on instead of getting parent with children that has a children and so on.
Any Idea? How to act?
I am not sure it will help, but this is the relevant code.
HierarchyItem result = new HierarchyItem();
var fullHierarchies = _entities.Hierarchies.Where(p => !p.Deleted).ToList();
var hierarchiesResult = _entities.Hierarchies.Where(p => !p.Deleted && p.Name.Contains(searchTerm)).ToList();
List<HierarchyItemWithParentAsHierarchyItem> itemsWithTrees = new List<HierarchyItemWithParentAsHierarchyItem>();
var hierarchyTop = new HierarchyItemWithParentAsHierarchyItem
{
HierarchyID = null,
label = "Organization",
Code = "0",
Path = string.Empty,
Level = 0,
Parent = null
};
foreach (var item in hierarchiesResult)
{
var hierarchy = new HierarchyItemWithParentAsHierarchyItem
{
HierarchyID = item.HierarchyID,
label = item.Name,
Code = item.Code,
Path = string.Empty,
Level = item.Level.Value,
};
hierarchy.Parent.Add(GetParent(fullHierarchies, item, hierarchyTop));
itemsWithTrees.Add(hierarchy);
}
private HierarchyItemWithParentAsHierarchyItem GetParent(List<CloudEntities.Hierarchy> fullHierarchies, CloudEntities.Hierarchy item, HierarchyItemWithParentAsHierarchyItem hierarchyTop)
{
try
{
HierarchyItemWithParentAsHierarchyItem tempHierarchyItem;
CloudEntities.Hierarchy tempHierarchy = fullHierarchies.FirstOrDefault(x => x.HierarchyID == item.ParentID);
if (tempHierarchy == null)
return hierarchyTop;
else
{
tempHierarchyItem = new HierarchyItemWithParentAsHierarchyItem()
{
HierarchyID = tempHierarchy.HierarchyID,
label = tempHierarchy.Name,
Code = tempHierarchy.Code,
Path = string.Empty,
Level = tempHierarchy.Level.Value
};
tempHierarchyItem.Parent.Add(GetParent(fullHierarchies, tempHierarchy, hierarchyTop));
}
return tempHierarchyItem;
}
catch (Exception ex)
{
}
}

Entity Framework - Accessing Model classes that have foreign/navigation key to themselves

I have the following Model, which can be a child of the same type, and/or have many children of the same type.
public class SystemGroupModel
{
public int Id { get; set; }
public int? ParentSystemGroupModelId { get; set; }
[ForeignKey("ParentSystemGroupModelId")]
public virtual SystemGroupModel ParentSystemGroupModel { get; set; }
[InverseProperty("ParentSystemGroupModel")]
public virtual ICollection<SystemGroupModel> SubSystemGroupModels { get; set; }
}
How can I get a specific SystemGroupModel by Id that is at an unknown depth, and include all of it's children, grandchildren, great-grandchildren, etc.?
This appears to be working, which means it will build a list of any given parent, as well as children at an unlimited depth of grandchildren, great-grandchildren, and so on.
Is this the right approach?
First I created this new class
public class SystemGroupWorkingClass
{
public SystemGroupModel SystemGroupModel { get; set; }
public bool WasChecked { get; set; }
}
Then I added this code
EDIT: Updated to include the loop that builds List<SystemGroupWorkingClass>
List<SystemGroupWorkingClass> tempListSystemGroups = new List<SystemGroupWorkingClass>();
//Get the SystemGroups that were selected in the View via checkbox
foreach (var systemGroupVM in viewModel.SystemGroups)
{
if (systemGroupVM.Selected == true)
{
SystemGroupModel systemGroupModel = await db.SystemGroupModels.FindAsync(systemGroupVM.Id);
SystemGroupWorkingClass systemGroupWorkingClass = new SystemGroupWorkingClass();
systemGroupWorkingClass.SystemGroupModel = systemGroupModel;
systemGroupWorkingClass.WasChecked = false;
systemGroupWorkingClass.Selected = true;
//Make sure tempListSystemGroups does not already have this systemGroupWorkingClass object
var alreadyAddedCheck = tempListSystemGroups
.FirstOrDefault(s => s.SystemGroupModel.Id == systemGroupVM.Id);
if (alreadyAddedCheck == null)
{
tempListSystemGroups.Add(systemGroupWorkingClass);
}
}
}
for (int i = 0; i < tempListSystemGroups.Count; i++)
{
if (tempListSystemGroups[i].WasChecked == false)
{
SystemGroupModel systemGroupModel2 = await db.SystemGroupModels.FindAsync(tempListSystemGroups[i].SystemGroupModel.Id);
//Get the children, if there are any, for the current parent
var subSystemGroupModels = systemGroupModel2.SubSystemGroupModels
.ToList();
//Loop through the children and add to tempListSystemGroups
//The children are added to tempListSystemGroups as it is being iterated over
foreach (var subSystemGroupModel in subSystemGroupModels)
{
SystemGroupModel newSystemGroupModel = await db.SystemGroupModels.FindAsync(subSystemGroupModel.Id);
SystemGroupWorkingClass subSystemGroupWorkingClass = new SystemGroupWorkingClass();
subSystemGroupWorkingClass.SystemGroupModel = newSystemGroupModel;
subSystemGroupWorkingClass.WasChecked = false;
tempListSystemGroups.Add(subSystemGroupWorkingClass);
}
}
//Mark the parent as having been checked for children
tempListSystemGroups[i].WasChecked = true;
}

Statement is not updating data item

I have this LINQ statement that tries to set the 1st element in the collection of string[]. But it doesn't work.
Below is the LINQ statement.
docSpcItem.Where(x => x.DocID == 2146943)
.FirstOrDefault()
.FinishingOptionsDesc[0] = "new value";
public string[] FinishingOptionsDesc
{
get
{
if (this._FinishingOptionsDesc != null)
{
return (string[])this._FinishingOptionsDesc.ToArray(typeof(string));
}
return null;
}
set { this._FinishingOptionsDesc = new ArrayList(value); }
}
What's wrong with my LINQ statement above?
Couple of things.. There are some problems with your get and set. I would just use auto properties like this..
public class DocSpcItem
{
public string[] FinishingOptionsDesc { get; set; }
public int DocID { get; set; }
}
Next for your linq statement, depending on the presence of an item with an id of 2146943 you might be setting a new version of the object rather than the one you intended. This should work..
[TestMethod]
public void Linq()
{
var items = new List<DocSpcItem>();
//2146943
for (var i = 2146930; i <= 2146950; i++)
{
items.Add(new DocSpcItem()
{ DocID = i
, FinishingOptionsDesc = new string[]
{ i.ToString() }
}
);
}
var item = items.FirstOrDefault(i => i.DocID == 2146943);
if (item != null)
{
item.FinishingOptionsDesc = new string[]{"The New Value"};
}
}
and
public class DocSpcItem
{
public string[] FinishingOptionsDesc { get; set; }
public int DocID { get; set; }
}

Categories