Search code examples
c#jsonlistjson.net

Remove JObject from JArray when the value matches an item in a list


I have an JArray as:

{[  
  {
    "value": "275869398483537748",
    "label": "AbhiTest1"
  },
  {
    "value": "275869398491926942",
    "label": "AbhiTest21"
  },
  {
    "value": "275869398487731826",
    "label": "AbhiTest3"
  }
]}

And I have a list as: List<String> IdsToDelete = new List<string>(); and IdsToDelete has an item whose value is "275869398491926942" which matches to 2nd JObject value in the above mentioned JArray.

How Can I remove this entire object from the JArray such that my output looks like:

   {[  
      {
        "value": "275869398483537748",
        "label": "AbhiTest1"
      },      
      {
        "value": "275869398487731826",
        "label": "AbhiTest3"
      }
    ]}

Please guide me.


Solution

  • Your json is not valid. You have to remove {} from both sides. After fixing you can use this code

    JArray items = JArray.Parse(json);
    
    items.Where(x=> idsToDelete.Contains( (string) x["value"])).ToList()
         .ForEach(tr => tr.Remove());