c#中的嵌套列表(父级和子级列表)

时间:2017-10-03 11:35:12

标签: c# list nested

我有一个列表,我想将其转换为树形结构。如何将其转换为树结构?

QuestionDetails.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

public class QuestionDetails
{
    public int QID { get; set; }
    public int QuestionID { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
    public int AnswerType { get; set; }
    //public string Question { get; set; }
    public IList<QuestionDetails> ChildLayers { get; private set; }  
    public QuestionDetails()
    {
        ChildLayers = new List<QuestionDetails>();
    }

}


public IList<QuestionDetails> daya()
{
    SqlConnection con = new SqlConnection("Data Source=ADMIN-PC;Initial Catalog=Test;Integrated Security=True");
    SqlCommand cmd = new SqlCommand(); //
    cmd.CommandText = "selectdata";
    cmd.Connection = con;
    cmd.CommandType = CommandType.StoredProcedure;
    con.Open();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    // da.Fill(ds.Tables["AnswerMaster"]);
    DataTable DT = new DataTable();
    DT = ds.Tables["Table"];
    DataTable DT1 = new DataTable();
    DT1 = ds.Tables["Table1"];

    IList<QuestionDetails> data = ConvertDataTable<QuestionDetails>(DT);


    IList<QuestionDetails> hierarcy = new List<QuestionDetails>();
    //IList<ChildLayers> hierarcy1 = new List<ChildLayers>();

    foreach (var layer in data)
    {

        var sublayers = data.Where(i => i.QID == layer.QuestionID && i.QID != 0);

         if (sublayers.Any())
         {
             hierarcy.Add(layer);
         }

         foreach (var sublayer in sublayers)
         {
             layer.ChildLayers.Add(sublayer);    
         }
    }

    return hierarcy; 
}

我希望以这种格式输出:

{
    question id=1
    Question ="asasaS"
    {
        ANSWER="SDASA";
        ANSWER="SADSAD";
        ANSWER="SADSA";
        ANSWER="SADSAD";
    }

    question id=2
    Question ="XCVXVXCVXC"
    {
        ANSWER="SDASA";
        ANSWER="SADSAD";
        ANSWER="SADSA";
        ANSWER="SADSAD";
    }
}

我想将列表数据作为嵌套列表。请帮助 我已经为列表创建了类。我有一个列表,我想将其转换为树结构。如何将其转换为树结构?

1 个答案:

答案 0 :(得分:1)

首先让我们谈谈你的对象:
QuestionDetails可以包含一个QuestionDetails列表,其中包含etc等列表。

QuestionDetails应包含Question及其Answer列表。答案不应该是Question

因此,让我们定义这些类:暂时忽略[ScriptIgnore]

class Question
{
    [ScriptIgnore]
    public int QID { get; set; }
    public int QuestionID { get; set; }
    public string QuestionText { get; set; }
    public IList<Answer> Answers { get; private set; }
    public Question()
    {
        Answers = new List<Answer>();
    }
    public Question( int questionID, string questionText, IList<Answer> answers )
    {
        Answers = answers;
        QuestionID = questionID;
        QuestionText = questionText;
    }

    public string ToWeirdString()
    {
        string sout = $"\tquestion id={QuestionID}\n" +
                        $"\tQuestion =\"{QuestionText}\"\n";
        sout += "\t{\n";
        foreach (var i in Answers)
        {
            sout += $"\t\tANSWER=\"{i.AnswerText}\";\n";
        }
        sout += "\t}\n";
        return sout;
    }
}

class Answer
{
    public Answer(string answerText, int answerType)
    {
        AnswerText = answerText;
        AnswerType = answerType;
    }

    public string AnswerText { get; set; }

    [ScriptIgnore]
    public int AnswerType { get; set; }
}

问题样本的初始化:

List<Question> sample = new List<Question> {
                            new Question(1, "text1", new List<Answer> {
                                                        new Answer("Answer 1",1),
                                                        new Answer("Answer 2",1),
                                                        new Answer("Answer 3",2),
                                                        new Answer("Answer 4",1)
                                                        }
                                        ),
                            new Question(2, "text2", new List<Answer> {
                                                        new Answer("Answer 5",1),
                                                        new Answer("Answer 6",3),
                                                        new Answer("Answer 7",1),
                                                        new Answer("Answer 8",4)
                                                        }
                                        )
                        };

获取奇怪的字符串:

var weirdString = "{\n"+string.Concat( sample.Select(x => x.ToWeirdString()+"\n\n") )+"}\n";

Json序列化有多简单?这很简单:

var json = new JavaScriptSerializer().Serialize(sample);

如果你错过了dll,请不要忘记你的using System.Web.Script.Serialization;并点击灯泡。

一个简单的界限,它看起来像这样:

[
   {
      "QuestionID":1,
      "QuestionText":"text1",
      "Answers":[
         {
            "AnswerText":"Answer 1"
         },
         {
            "AnswerText":"Answer 2"
         },
         {
            "AnswerText":"Answer 3"
         },
         {
            "AnswerText":"Answer 4"
         }
      ]
   },
   {
      "QuestionID":2,
      "QuestionText":"text2",
      "Answers":[
         {
            "AnswerText":"Answer 5"
         },
         {
            "AnswerText":"Answer 6"
         },
         {
            "AnswerText":"Answer 7"
         },
         {
            "AnswerText":"Answer 8"
         }
      ]
   }
]

Ps:[ScriptIgnore]告诉JavaScriptSerializer忽略此属性。