【问题标题】:How do i create name of List dynamically?如何动态创建列表名称?
【发布时间】:2014-04-28 10:41:03
【问题描述】:

我正在尝试创建 =>

{
  "Data1":{
     "DataListOne": [0, 1],
     "DataListTwo": [1, 0, 0, 0]
          },
  "Data2":{
     "DataListOne": [1, 0],
     "DataListTwo": [0, 0, 0, 1]
          },
  "Data-n" : { 
     "DataListOne": [1, 0],
     "DataListTwo": [0, 1, 0, 0]
          } 
}

动态列出从 Data1 到 Data-n 的未指定在哪一点我需要停止该 List 并且还需要 Data1 到 Data-n 内的两个列表(DataListOne,DataListTwo)。

我不知道如何动态创建从 Data1 到 Data-n 的列表以及从 Data1 到 Data-n 的动态列表中的两个列表(DataListOne、DataListTwo)

请帮帮我。

【问题讨论】:

    标签: asp.net asp.net-mvc-3 asp.net-mvc-4 c#-4.0


    【解决方案1】:

    我会为此使用 Json.NET - 它可以让您动态构建 JSON:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Newtonsoft.Json.Linq;
    
    class Program
    {
        static void Main(string[] args)
        {
            var pairs = new List<ListPair>
            {
                new ListPair
                {
                    DataListOne = { 0, 1 },
                    DataListTwo = { 1, 0, 0, 0 }
                },
                new ListPair
                {
                    DataListOne = { 1, 0 },
                    DataListTwo = { 0, 0, 0, 1 }
                },
                new ListPair
                {
                    DataListOne = { 1, 0 },
                    DataListTwo = { 0, 1, 0, 0 }
                },
            };
    
            JObject json = CreateJson(pairs);
            Console.WriteLine(json);
        }
    
        static JObject CreateJson(List<ListPair> pairs)
        {
            return new JObject(pairs.Select(
               (pair, index) => new JProperty("Data" + (index + 1),
                                              JObject.FromObject(pair))));
    
        }
    
        class ListPair
        {
            public List<int> DataListOne, DataListTwo;
    
            public ListPair()            
            {
                DataListOne = new List<int>();
                DataListTwo = new List<int>();
            }
        }
    }
    

    另一方面,我认为只在 JSON 中创建一个数组而不是动态生成名称会更简洁。

    【讨论】:

    • 由编码 Jon Skeet 自己的神回答......你还想要什么 OP :D
    • 非常感谢您的帮助。它真的有帮助。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 2018-03-03
    • 1970-01-01
    • 2013-11-18
    相关资源
    最近更新 更多