此算法所用数据库为整个河南省地区(省、市、县)
/* * 无限级树算法 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace ConApp1 { class Program { static void Main(string[] args) { //Test.Dt(); TestTree("0", 0); Console.ReadKey(true); } /* * 无限级树算法 */ static DataTable dt = Test.Dt(); static int No = dt.Rows.Count; public static void TestTree(string f_id, int level) { int newlevel = 0; foreach (DataRow item in dt.Rows) { if (item.ItemArray[3].ToString().Trim() == f_id) { for (int m = 0; m < level; m++) { Console.Write("{0}","--"); } newlevel = level + 1; Console.WriteLine("{0}", item.ItemArray[2].ToString()); TestTree(item.ItemArray[1].ToString(), newlevel); } } } } /// <summary> /// 数据操作类 /// </summary> static class Test { public static SqlConnection Con() { SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Area;Integrated Security=True"); con.Open(); return con; } public static DataTable Dt() { string sqlStr = "select * from [dbo].[Area]"; SqlCommand cmd = new SqlCommand(sqlStr, Con()); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); return dt; } } }