【问题标题】:Sort a list of objects and convert into a list of JObjects对对象列表进行排序并转换为对象列表
【发布时间】:2021-07-18 21:06:11
【问题描述】:

我是 C# 编程新手,如有任何帮助,我将不胜感激。因为这对于 c# 开发人员来说可能是一件简单的事情。我尝试了很多东西,但是当我尝试开发这个时,Newtonsoft JObjects 中出现了类型不匹配或编译错误。

我有一个对象列表,例如

List<ContextResult> formOutputs ->

[0] = (section 1, Button, true),
[1] = (section 1, TextBox, anyname),
[2] = (section 2, Button, false)

public class ContextResult
    {
        public string Section { get; set; }
        public string Key{ get; set; }
        public string Value { get; set; }
    }

我需要将其分类,然后使用 Newtonsoft.Json.Linq 将其转换为 JObject 列表。 JSON 格式的输出应如下所示,

"section 1":{
"Button": "true",
"TextBox": "anyname"
 },
"section 2":{
"Button": "false"
 }

请注意,我已经将 formOutputs 排序为升序,并使用 GroupBy 分组以删除重复项。

【问题讨论】:

  • 但是你的输出不像 JSON 格式。 JSON 格式看起来像 [{Object object},{Object object},{Object object}]
  • @SwissCodeMen 我很抱歉。我更新了问题

标签: c# json listobject jobjectformatter


【解决方案1】:

我不会使用 JObjects,而是将您的数据转换为所需的结构,然后将其序列化。

以下是对您的数据进行处理的方法:

var o = formOutputs
     .GroupBy(o => o.Section) 
     .ToDictionary(g => g.Key,g => g.ToDictionary(x => x.Key, x => x.Value));   

这是一个带有 cmets 的版本:

var o = formOutputs
    .GroupBy( o => o.Section) // For the example data we now have groups: 'section 1', 'section 2'
    .ToDictionary( 
        keySelector: g => g.Key, // this 'Key' is the group's key (so o.Section), not the Key property of ContextResult
        elementSelector: g => g.ToDictionary( 
                keySelector: x =>  x.Key, 
                elementSelector: x => x.Value));

测试:

var formOutputs = new List<ContextResult> {
    new ContextResult { Section = "section 1", Key = "Button", Value = "true"},
    new ContextResult { Section = "section 1", Key = "TextBox",Value = "anyname"},
    new ContextResult { Section = "section 2", Key = "Button", Value = "false"}
    };

var o = formOutputs
    .GroupBy(o => o.Section) 
    .ToDictionary(g => g.Key,g => g.ToDictionary(x =>  x.Key, x => x.Value));    

Console.WriteLine(JsonConvert.SerializeObject(o, Formatting.Indented));

输出:

{
  "section 1": {
    "Button": "true",
    "TextBox": "anyname"
  },
  "section 2": {
    "Button": "false"
  }
}

【讨论】:

  • 非常感谢!!你让我今天一整天都感觉很好。我为此苦苦挣扎了好几个小时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-03
  • 2018-10-20
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多