【问题标题】:How to put multiple values in Dictionary instances using LINQ?如何使用 LINQ 在 Dictionary 实例中放置多个值?
【发布时间】:2020-05-16 07:50:00
【问题描述】:

我的 Json 响应如下:

{"d":
{"RowData": 
[{"GenreId":11,"GenreName":"Musical","subjecturl":"subjecturl_1","logourl":"logourl_1"},
{"GenreId":12,"GenreName":"kids","subjecturl":"subjecturl_2","logourl":"logourl_2"},
{"GenreId":13,"GenreName":"other","subjecturl":"subjecturl_3","logourl":"logourl_3"},
{"GenreId":14,"GenreName":"Musical","subjecturl":"subjecturl_4","logourl":"logourl_4"},
{"GenreId":15,"GenreName":"Music","subjecturl":"subjecturl_5","logourl":"logourl_5"},
{"GenreId":16,"GenreName":"Faimaly","subjecturl":"subjecturl_6","logourl":"logourl_6"},
{"GenreId":17,"GenreName":"other","subjecturl":"subjecturl_7","logourl":"logourl_7"},
{"GenreId":18,"GenreName":"other","subjecturl":"subjecturl_8","logourl":"logourl_8"},
{"GenreId":19,"GenreName":"kids","subjecturl":"subjecturl_9","logourl":"logourl_9"},
{"GenreId":20,"GenreName":"Musical","subjecturl":"subjecturl_10","logourl":"logourl_10"},
{"GenreId":21,"GenreName":"other","subjecturl":"subjecturl_11","logourl":"logourl_11"}]}}

使用上面的响应,我尝试做出如下响应:

{"rows": [{
        "title": "Musical",
        "items": [{"hdsubjecturl": "subjecturl_1"},{"hdsubjecturl": "subjecturl_4"},{"hdsubjecturl": "subjecturl_10"}]
        },{
        "title": "kids",
        "items": [{"hdsubjecturl": "subjecturl_2"},{"hdsubjecturl": "subjecturl_9"}]
        },{
        "title": "Music",
        "items": [{"hdsubjecturl": "subjecturl_5"}]
        },{
        "title": "other",
        "items": [{"hdsubjecturl": "subjecturl_3"},{"hdsubjecturl": "subjecturl_7"},{"hdsubjecturl": "subjecturl_8"},{"hdsubjecturl": "subjecturl_11"}]
        },{
        "title": "Faimaly",
        "items": [{"hdsubjecturl": "subjecturl_6"}]
        }]
}

我的代码如下:

JObject Root = JObject.Parse(jsonData["d"].ToString());
var unique = Root["RowData"].GroupBy(x => x["GenreName"]).Select(x => x.First()).ToList(); // here fetch 5 record
foreach (var un in unique)
{
      var GenreName = new
      {
               title = un["GenreName"],
               items = new
               {
                     hdsubjecturl = "logourl"
               }
      };
      var GenreNamereq = JsonConvert.SerializeObject(GenreName, Newtonsoft.Json.Formatting.Indented);
      genstr.Append(GenreNamereq, 0, GenreNamereq.Length);
      genstr.Append(",");
      using (System.IO.StreamWriter file = new System.IO.StreamWriter(subdir + "\\GenreName.json"))
      {
              string st = genstr.ToString().Substring(0, (genstr.Length - 1));
              file.WriteLine("{\n\"rows\": [\n" + st + "\n}"); //seasion number 21 terminate
              file.Close();
      }
}

使用上面的代码,我的第一个字段的输出如下:

{"rows":
    [{
       "title": "Musical",
         "items": {
            "hdsubjecturl": "logourl"
          }
    }]
}

使用下面的代码,我尝试使用特定字段获取多个值:

List<string> CategoryList = new List<string>();
var unique = Root["RowData"].GroupBy(x => x["GenreName"]).Select(x => x.First()).ToList(); // here fetch 8 record
foreach (var cat in unique)
{
     CategoryList.Add(cat["GenreName"].ToString());
}

List<List<string>> myList = new List<List<string>>();

for (int i=0;i<CategoryList.Count();i++)
{
     var results = from x in Root["RowData"]
                   where x["GenreName"].Value<string>() == CategoryList[i]
                   select x;

                   foreach (var token in results)
                   {
                      Console.WriteLine(token["logourl"]);
                   }
                   // myList.Add(results);
}

在第一个代码中,我使用 JObject 来获取根节点。但是,使用上面的查询,默认情况下需要 JTocken。所以,我在这里使用了 foreach 循环。 我使用Dictionary instances 创建 JSON。使用此代码,我成功地在 for 循环中获取了 hdsubjecturl。但是,我不知道如何在 Dictionary 实例中放置多个值。因为我使用唯一查询仅获得一次标题字段,而 hdsubjetcurl 中的项目字段不止一个。有谁知道这怎么可能?

【问题讨论】:

    标签: c# json linq dictionary


    【解决方案1】:

    您可以通过GenreName 标记对RowData 进行分组,然后使用ToDictionary 方法获取结果字典并将其映射到所需的结构(使用titlehdsubjecturl)。最后使用JObject.FromObject创建一个结果对象

    var json = JObject.Parse(jsonString);
    
    var data = json["d"]?["RowData"]
        .GroupBy(x => x["GenreName"], x => x["subjecturl"])
        .ToDictionary(g => g.Key, g => g.ToList())
        .Select(kvp => new { title = kvp.Key, items = kvp.Value.Select(x => new { hdsubjecturl = x }) });
    
    var result = JObject.FromObject(new { rows = data });
    Console.WriteLine(result);
    

    它会给你预期的结果。

    编辑:根据 cmets,GroupBySelect 表达式应更新为在结果 title 项目中映射多个属性

    var data = json["d"]?["RowData"]
        .GroupBy(x => x["GenreName"])
        .ToDictionary(g => g.Key, g => g.ToList())
        .Select(kvp => new
        {
            title = kvp.Key,
            items = kvp.Value.Select(x => new { hdsubjecturl = x["subjecturl"], url = x["logourl"] })
        });
    
    var result = JObject.FromObject(new { rows = data });
    

    【讨论】:

    • 感谢您的出色回答。它正在工作,我尝试使用您的查询添加 logourl,如下所示 "items": [{"hdsubjecturl": "subjecturl_5","url":"logourl_5"}] 但是,运气不好。可以使用相同的查询添加,或者需要不同的查询来添加 logourl。
    • @NikunjChaklasiya 在您的问题的预期回复中没有logourl。您可以为此稍微重写组,请参阅更新的答案
    【解决方案2】:

    考虑尝试这段代码,(使用 Newtonsoft Json 反序列化器);

        public partial class Root
        {
            public D D { get; set; }
        }
    
        public partial class D
        {
            public RowDatum[] RowData { get; set; }
        }
    
        public partial class RowDatum
        {
            public long GenreId { get; set; }
            public string GenreName { get; set; }
            public string Subjecturl { get; set; }
            public string Logourl { get; set; }
        }
    
        public partial class Response
        {
            public Row[] Rows { get; set; }
        }
    
        public partial class Row
        {
            public string Title { get; set; }
            public Item[] Items { get; set; }
        }
    
        public partial class Item
        {
            public string Hdsubjecturl { get; set; }
        }
        public class Program
        {
            public static void Main(string[] args)
            {
    
                var json =
                    @"{""d"":{""RowData"":[{""GenreId"":11,""GenreName"":""Musical"",""subjecturl"":""subjecturl_1"",""logourl"":""logourl_1""},{""GenreId"":12,""GenreName"":""kids"",""subjecturl"":""subjecturl_2"",""logourl"":""logourl_2""},{""GenreId"":13,""GenreName"":""other"",""subjecturl"":""subjecturl_3"",""logourl"":""logourl_3""},{""GenreId"":14,""GenreName"":""Musical"",""subjecturl"":""subjecturl_4"",""logourl"":""logourl_4""},{""GenreId"":15,""GenreName"":""Music"",""subjecturl"":""subjecturl_5"",""logourl"":""logourl_5""},{""GenreId"":16,""GenreName"":""Faimaly"",""subjecturl"":""subjecturl_6"",""logourl"":""logourl_6""},{""GenreId"":17,""GenreName"":""other"",""subjecturl"":""subjecturl_7"",""logourl"":""logourl_7""},{""GenreId"":18,""GenreName"":""other"",""subjecturl"":""subjecturl_8"",""logourl"":""logourl_8""},{""GenreId"":19,""GenreName"":""kids"",""subjecturl"":""subjecturl_9"",""logourl"":""logourl_9""},{""GenreId"":20,""GenreName"":""Musical"",""subjecturl"":""subjecturl_10"",""logourl"":""logourl_10""},{""GenreId"":21,""GenreName"":""other"",""subjecturl"":""subjecturl_11"",""logourl"":""logourl_11""}]}}";
    
                var root = JsonConvert.DeserializeObject<Root>(json);
    
                var rows = root.D.RowData.ToLookup(d => d.GenreName)
                    .Select(g => new Row()
                    {
                        Title = g.Key,
                        Items = g.ToList().Select(rd => new Item() {Hdsubjecturl = rd.Logourl}).ToArray()
                    }).ToArray();
    
                var response = new Response()
                {
                    Rows = rows
                }; // reponse is the type of Json Response you wanted to achieve
    
                Console.WriteLine();
    
            }
    
    
        }
    

    【讨论】:

      猜你喜欢
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      相关资源
      最近更新 更多