当前位置:编程学习 > C#/ASP.NET >>

题目如下,最好能用递归

Id      CategoryName   ParentId
1 ic         0         
2 T卡         0         
3 三极管        0         
4 贴片         1         
6 Tm445      4         
7 B445       4         
8 DF23       2         
10 bn22       4         
11 BB33       7     


数据表中的数据结构如上,要把取出来的数据拼接成下列字符串:
[{'val':'1','txt':'ic','menu':[{'val':'4','txt':'贴片','menu':[{'val':'7','txt':'B445'},{'val':'8','txt':'DF23'},{'val':'10','txt':'bn22'}]}]},{'val':'2','txt':'T卡','menu':[{'val':'6','txt':'Tm445'}]},{'val':'3','txt':'三极管'}]

如题没有子集的格式为{'val':'3','txt':'三极管'},
有子集的为{'val':'2','txt':'T卡','menu':[{'val':'6','txt':'Tm445'}]}
有三级子集的为{'val':'1','txt':'ic','menu':[{'val':'4','txt':'贴片','menu':[{'val':'7','txt':'B445'},{'val':'8','txt':'DF23'}

然后以此类推,可能有4级、5级。 --------------------编程问答-------------------- 这帖子好象眼熟啊 --------------------编程问答-------------------- 是的,我上了三遍同样的帖子
引用 1 楼 zzzzv0 的回复:
这帖子好象眼熟啊
--------------------编程问答--------------------
class MyClass
{
    public MyClass(string onlyMenu)
    {
        this.Val = 0;
        this.Txt = "";
        this.Menu = this.Split(onlyMenu);
        this.Parent = 0;
    }

    public MyClass(string input, int parent)
    {
        Match m = Regex.Match(input, @"'val':'([^']+)','txt':'([^']+)','menu':\[(.*)\]");
        if (m.Success)
        {
            this.Val = int.Parse(m.Groups[1].Value);
            this.Txt = m.Groups[2].Value;
            this.Parent = parent;
            this.Menu = this.Split(m.Groups[3].Value);
            return;
        }

        m = Regex.Match(input, @"'val':'([^']+)','txt':'([^']+)");
        if (m.Success)
        {
            this.Val = int.Parse(m.Groups[1].Value);
            this.Txt = m.Groups[2].Value;
            this.Parent = parent;
            this.Menu = new MyClass[0];
            return;
        }

        throw new FormatException();
    }

    public int Val { get; set; }
    public string Txt { get; set; }
    public MyClass[] Menu { get; set; }
    public int Parent { get; set; }

    public MyClass[] Split(string input)
    {
        List<MyClass> list = new List<MyClass>();
        int brace = 0;
        int left = 0;
        int count = 0;

        for (int i = 0; i < input.Length; i++)
        {
            if (input[i] == '{') brace++;
            if (input[i] == '}') brace--;
            if (brace == 0)
            {
                if (count != 0)
                {
                    string sub = input.Substring(left, count);
                    list.Add(new MyClass(sub + '}', this.Val));
                }
                left = i + 1;
                count = 0;
            }
            else if (brace > 0) count++;
            else throw new FormatException();
        }

        if (brace != 0) throw new FormatException();
        return list.ToArray();
    }
}

static void EnumAll(MyClass parent, ICollection<MyClass> collection)
{
    if (collection == null) throw new ArgumentNullException();
    collection.Add(parent);
    foreach (var item in parent.Menu)
    {
        EnumAll(item, collection);
    }
}

static void Main(string[] args)
{
    string input = @"[{'val':'1','txt':'ic','menu':[{'val':'4','txt':'贴片','menu':[{'val':'7','txt':'B445'},{'val':'8','txt':'DF23'},{'val':'10','txt':'bn22'}]}]},{'val':'2','txt':'T卡','menu':[{'val':'6','txt':'Tm445'}]},{'val':'3','txt':'三极管'}]";
    MyClass c = new MyClass(input);
    List<MyClass> list = new List<MyClass>();
    EnumAll(c, list);
    list.Sort((p, q) => p.Val - q.Val);
    Console.WriteLine("Id CategoryName ParentId");
    foreach (var item in list)
    {
        Console.WriteLine("{0,2} {1,12} {2,8}", item.Val, item.Txt, item.Parent);
    }
    Console.ReadKey();
}

把昨天的改了改,又发上来了

你给的字符串里只有10个,没有11。。。

昨天版主的正则我还没弄明白,学习ing --------------------编程问答-------------------- 输出
Id CategoryName ParentId
 0                     0
 1           ic        0
 2           T卡        0
 3          三极管        0
 4           贴片        1
 6        Tm445        2
 7         B445        4
 8         DF23        4
10         bn22        4 --------------------编程问答--------------------
引用 4 楼 zzzzv0 的回复:
输出
Id CategoryName ParentId
 0                     0
 1           ic        0
 2           T卡        0
 3          三极管        0
 4           贴片        1
 6        Tm445        2
 7         B4……
唉,你没懂我的意思,上面给的是数据库中的数据,然后读取出来,在拼接成上面发的那一段数据 --------------------编程问答-------------------- 晕 我昨天不看题在胡写什么啊
听别人说有json.net这么个东西
http://json.codeplex.com/
学习了一下
[JsonObject(MemberSerialization.OptOut)]
class MyClass
{
    [JsonProperty(PropertyName = "val")]
    public string Id { get; set; }
    [JsonProperty(PropertyName = "txt")]
    public string CategoryName { get; set; }
    [JsonProperty(PropertyName = "menu", NullValueHandling = NullValueHandling.Ignore)]
    public List<MyClass> Menu { get; set; }
    [JsonIgnore]
    public string ParentId { get; set; }
}

static void Main(string[] args)
{
    string input = @"1 ic 0 
                2 T卡 0 
                3 三极管 0 
                4 贴片 1 
                6 Tm445 4 
                7 B445 4 
                8 DF23 2 
                10 bn22 4 
                11 BB33 7";
    Dictionary<string, MyClass> dict = new Dictionary<string, MyClass>();
    foreach (var item in input.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
    {
        string[] strs = item.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        MyClass tmp = new MyClass()
        {
            Id = strs[0],
            CategoryName = strs[1],
            Menu = new List<MyClass>(),
            ParentId = strs[2]
        };
        dict.Add(strs[0], tmp);
        if (dict.ContainsKey(strs[2]))
        {
            dict[strs[2]].Menu.Add(tmp);
        }
    }

    foreach (var item in dict)
    {
        if (item.Value.Menu.Count == 0)
        {
            item.Value.Menu = null;
        }
    }

    string result = JsonConvert.SerializeObject(dict.Values.Where(p => p.ParentId == "0"));
    Console.WriteLine(result);
    Console.ReadKey();
}

添加引用\bin\net40\Newtonsoft.Json.dll,我用的4.0
然后using Newtonsoft.Json; --------------------编程问答-------------------- 递归添加到集,在序列化
[DataContract]
public class Category
{
    [DataMember(Name = "val", Order = 0)]
    public int ID { get; set; }
    [DataMember(Name = "txt", Order = 1)]
    public string CategoryName { get; set; }
    [DataMember(Name = "menu", Order = 2, EmitDefaultValue = false)]
    public List<Category> Categorys { get; set; }
}
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("CategoryName", typeof(string));
        dt.Columns.Add("ParentID", typeof(int));
        dt.Rows.Add(new object[] { 1, "ic", 0 });
        dt.Rows.Add(new object[] { 2, "T卡", 0 });
        dt.Rows.Add(new object[] { 3, "三极管", 0 });
        dt.Rows.Add(new object[] { 4, "帖片", 1 });
        dt.Rows.Add(new object[] { 6, "Tm445", 4 });
        dt.Rows.Add(new object[] { 7, "B445", 4 });
        dt.Rows.Add(new object[] { 8, "DF23", 2 });
        dt.Rows.Add(new object[] { 10, "bn22", 4 });
        dt.Rows.Add(new object[] { 11, "BB33", 7 });
        List<Category> list = new List<Category>();
        GetSon(dt, 0, list);
        DataContractJsonSerializer json = new DataContractJsonSerializer(list.GetType());
        MemoryStream ms = new MemoryStream();
        json.WriteObject(ms, list);
        string result = Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        ms.Dispose();
        Response.Write(result);
    }
    public void GetSon(DataTable dt, int ParentID, List<Category> list)
    {
        DataRow[] row = dt.Select("ParentID=" + ParentID);
        foreach (DataRow r in row)
        {
            int id = Convert.ToInt32(r["ID"]);
            Category c = new Category() { ID = id, CategoryName = r["CategoryName"].ToString(), Categorys = new List<Category>() };
            list.Add(c);
            GetSon(dt, id, c.Categorys);
            if (c.Categorys.Count == 0)
                c.Categorys = null;
        }
    }
}

/*
[{"val":1,"txt":"ic","menu":[{"val":4,"txt":"帖片","menu":[{"val":6,"txt":"Tm445"},{"val":7,"txt":"B445","menu":[{"val":11,"txt":"BB33"}]},{"val":10,"txt":"bn22"}]}]},{"val":2,"txt":"T卡","menu":[{"val":8,"txt":"DF23"}]},{"val":3,"txt":"三极管"}] 
*/
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,