JSON - LINQ查询对象或数组以使用相同的键值对对两个数据进行分组

时间:2017-11-03 09:00:10

标签: c# json linq

考虑我有一个JSON数据:

{
"entities":[
    {
      "republish": false,
      "OrgID": "",
      "createdby": "730",
      "questions": [
        {
          "sequence": "5",
          "QuestionId": "57BB6DDC-A90A-10EE-E224-EC658A825871",
          "metadata": [
            {
              "key": "Group",
              "value": 0
            },
            {
              "key": "Part",
              "value": "0"
            }
          ]
        },
        {
          "sequence": "4",
          "QuestionId": "57BB6DDC-A90A-10EE-E224-EC658A825871",
          "metadata": [
            {
              "key": "Group",
              "value": 1
            },
            {
              "key": "Part",
              "value": "A"
            }
          ]
        },
        {
          "sequence": "3",
          "QuestionId": "57BB6DDC-A90A-10EE-E224-EC658A825871",
          "metadata": [
            {
              "key": "Group",
              "value": 1
            },
            {
              "key": "Part",
              "value": "B"
            }
          ]
        }
        ]
    }
    ]
}

正如您所看到的,我有一个可用的问题列表,在每个问题中,我都有一个包含键值对的元数据。

以上示例演示,我有3个问题,其中2个问题,元数据键值是"组1"。

现在我想做的是将问题与相同的键值对结合起来并将其视为一个。

所以在我的最后一个案例中,我将有2个问题而不是3个问题。在这个问题中,将有两个单独的问题。

我希望使用Linq查询来实现这一点。如果可能的话,如果需要,请使用Newtonsoft进行解析。我长期坚持这一点。

我做过的事情:

public virtual HttpResponseMessage AddQuestionsToStandardMaster(TaxonomyMetaData objQuestion)
    {
        List<ResponseEntity> objResponseList = new List<ResponseEntity>();
        try
        {
            if (ModelState.IsValid)
            {
                foreach (var objEntity in objQuestion.Entities)
                {
                    EntityResponse objentityresponse = new EntityResponse();
                    ResponseEntity objResponse = new ResponseEntity();
                }
                 List<Question> objQuestionList = new List<Question>();
                            if (objEntity.Questions.Length > 0)
                            {
                             foreach (var item in objEntity.Questions)
                                {
                                    int questionTypeid = 0;

                                    dynamic objQuestionJson = JObject.Parse(item.ToString())
                            }
                        }
            }
            Question objCurrentQuestion = new Question();
                                    Question objQuestionforDelete = new Question();
                                    JObject itemToParese = new JObject();
                                    string SingleQuestionJson = objQuestionJson.GetValue("QuestionData").ToString();
                                    string questionstem = "";
                                    Regex rgx = new Regex("/\'");
                                    objCurrentQuestion.Sequence = Convert.ToInt32(objQuestionJson.GetValue("sequence"));
                                    objCurrentQuestion.tag = objQuestionJson.tag.ToObject<JToken[]>(); ;
                                    objCurrentQuestion.metadata = objQuestionJson.metadata.ToObject<JToken[]>();
                                    objCurrentQuestion.SingleQuestionJson = rgx.Replace(SingleQuestionJson, "'");
                                    objCurrentQuestion.QuestionsType = questionTypeid;
                                    objCurrentQuestion.QuestionsId = new Guid(objQuestionJson.GetValue("QuestionId").ToString());
                                    objCurrentQuestion.VersionNo = Convert.ToInt32(objQuestionJson.GetValue("VersionNo"));
                                    objCurrentQuestion.DisplayQuestionId = Convert.ToString(objQuestionJson.GetValue("DisplayQuestionId"));
                                    objCurrentQuestion.OriginalQuestionId = Convert.ToString(objQuestionJson.GetValue("OriginalQuestionId"));
                                    objCurrentQuestion.PassageText = Convert.ToString(objQuestionJson.GetValue("passage_text"));
                                    objCurrentQuestion.PassageCode = Convert.ToString(objQuestionJson.GetValue("passage_id"));
                                    objCurrentQuestion.PassageTitle = Convert.ToString(objQuestionJson.GetValue("passage_title"));
                                    objCurrentQuestion.IsPublished = Convert.ToByte(true);
                                    objCurrentQuestion.ProductId = objEntity.ProductID;

                                    foreach (var metadata in objCurrentQuestion.metadata)
                                    {
                                        switch (metadata["key"].ToString())
                                        {
                                            case "Group":
                                                objCurrentQuestion.Group = Convert.ToInt32(metadata["value"].ToString());
                                                break;

                                            case "Part":
                                                objCurrentQuestion.Part = metadata["value"].ToString();
                                                break;
                                        }

                                    }
                                    objQuestionList.Add(objCurrentQuestion);
                                    int counter = 1;
                                //Here I get the data in a group which needs to coverted to JSOn and then replace the original JSON data with this. But I know this is irrelevant to what we need to achieve.
                                var yui = objQuestionList.Where(tma => tma.Group == counter).Select(t => t).GroupBy(s => new { s.Group }).Where(p => p.Count() > 1).ToList();

                                //After proper conversion I need to enter this data to a database.

1 个答案:

答案 0 :(得分:0)

我有点不清楚你的意思是什么

  

将问题与相同的键值对结合起来并将其视为一个

但是,您可以通过JSON将元组分组到元数据组中,您可以根据需要自定义选择。

var text = @"{
""entities"":[
    {
      ""republish"": false,
      ""OrgID"": """",
      ""createdby"": ""730"",
      ""questions"": [
        {
          ""sequence"": ""5"",
          ""QuestionId"": ""57BB6DDC-A90A-10EE-E224-EC658A825871"",
          ""metadata"": [
            {
              ""key"": ""Group"",
              ""value"": 0
            },
            {
              ""key"": ""Part"",
              ""value"": ""0""
            }
          ]
        },
        {
          ""sequence"": ""4"",
          ""QuestionId"": ""57BB6DDC-A90A-10EE-E224-EC658A825871"",
          ""metadata"": [
            {
              ""key"": ""Group"",
              ""value"": 1
            },
            {
              ""key"": ""Part"",
              ""value"": ""A""
            }
          ]
        },
        {
          ""sequence"": ""3"",
          ""QuestionId"": ""57BB6DDC-A90A-10EE-E224-EC658A825871"",
          ""metadata"": [
            {
              ""key"": ""Group"",
              ""value"": 1
            },
            {
              ""key"": ""Part"",
              ""value"": ""B""
            }
          ]
        }
        ]
    }
    ]
}";
            var json = JObject.Parse(text);

            var groupedData = from entity in json["entities"]
                              from question in  entity["questions"]
                              group question by question["metadata"][0]["value"] into questionGroup
                              select questionGroup;

            foreach (var data in groupedData)
            {
                Console.WriteLine("_____________________");
                Console.WriteLine("Group");
                Console.WriteLine(data.Key);

                foreach (var question in data)
                {
                    Console.WriteLine(question["QuestionId"]);
                }
                Console.WriteLine("_____________________");
            }

如果“Group”并不总是数组中的第一项,那么

question["metadata"].First(md => md.Value<string>("key") == "Group")["value"]

得到它。