Untitled
unknown
csharp
10 months ago
1.4 kB
6
Indexable
using System;
using System.Collections.Generic;
using System.Data;
public class Parent
{
public int ParentId { get; set; }
public string ParentName { get; set; }
public List<Child> Children { get; set; } = new List<Child>();
}
public class Child
{
public int ChildId { get; set; }
public string ChildName { get; set; }
}
public class Example
{
public static List<Parent> MapToParentChild(DataTable dataTable)
{
var parents = new Dictionary<int, Parent>();
foreach (DataRow row in dataTable.Rows)
{
int parentId = Convert.ToInt32(row["ParentId"]);
string parentName = row["ParentName"].ToString();
int childId = Convert.ToInt32(row["ChildId"]);
string childName = row["ChildName"].ToString();
// Check if the parent already exists
if (!parents.ContainsKey(parentId))
{
parents[parentId] = new Parent
{
ParentId = parentId,
ParentName = parentName
};
}
// Add the child to the parent's list
parents[parentId].Children.Add(new Child
{
ChildId = childId,
ChildName = childName
});
}
return new List<Parent>(parents.Values);
}
}Editor is loading...
Leave a Comment