:次のような方法から
public class Category
{
public string Id
{
get;
set;
}
public string Name
{
get;
set;
}
public List<Category> Categories
{
get;
set;
}
}
[TestFixture]
public class Recursion
{
[Test]
public void Test()
{
using (var conn = new SqlConnection(@"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=foo"))
{
var flatResult = conn.Query<Category>(@"select '1' as Id, 'Cat 1' as Name, ParentId = null
union all select '2' as Id, 'Cat 2' as Name, '1' as ParentId
union all select '3' as Id, 'Cat 3' as Name, '2' as ParentId
union all select '4' as Id, 'Cat 4' as Name, null as ParentId
union all select '5' as Id, 'Cat 5' as Name, 4 as ParentId");
var tree = BuildTree(flatResult.ToList());
}
}
private static IEnumerable<Category> BuildTree(List<Category> items)
{
items.ForEach(i => i.Categories = items.Where(ch => ch.ParentId == i.Id).ToList());
return items.Where(i => i.ParentId == null).ToList();
}
}