Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

301
Views
How to delete property from dynamic JObject programmatically

Below is the code

json - just want JsonLookupData in the response

{
  "LookupType": "ABC",
  "BusSegmentName": "Test",
  "PolcyObjectId": "999",
  "JsonLookupData": {
    "data":    {
      "OBJ_ID": "9393",
      "ABC": "JAJA",
      "XYZ": "LL",
      "AAA": "250.00"
    }
  }
}

public new dynamic input { get; set; }

//initialization 
 input = JsonConvert.DeserializeObject(jsonInput.ToString());

//trying to remove all attributes except JsonLookupData
input.Properties().Where
                 (x => !x.Name.Equals("JsonLookupData")).ToList().ForEach(x => x.Remove());
  

Is there any way to delete the properties directly from the dynamic input (Don't want to assign it to JObject first).

above code is giving the below error

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

While a JObject is still the right choice, you can still use dynamic as long as you do not use lambda expressions that are reliant on dynamic dispatch.

By assigning the output of input.Properties() to a non-dynamic type (IEnumerable<dynamic>), we can perform operations in a lambda expression.

input = JsonConvert.DeserializeObject(jsonInput.ToString());

IEnumerable<dynamic> props = input.Properties();
props.Where(x => !x.Name.Equals("JsonLookupData")).ToList().ForEach(x => x.Remove());

string xx = JsonConvert.SerializeObject(input);

This outputs:

{"JsonLookupData":{"data":{"OBJ_ID":"9393","ABC":"JAJA","XYZ":"LL","AAA":"250.00"}}}

Alternatively, you can avoid Linq altogether.

input = JsonConvert.DeserializeObject(jsonInput);

// create a separate tracking collection so that we 
// do not modify the collection we are iterating
var propsToRemove = new List<JProperty>();

foreach (var prop in input.Properties())
{
    if (!prop.Name.Equals("JsonLookupData"))
    {
        propsToRemove.Add(prop);
    }
}

propsToRemove.ForEach(x => x.Remove());

string xx = JsonConvert.SerializeObject(input);

This outputs:

{"JsonLookupData":{"data":{"OBJ_ID":"9393","ABC":"JAJA","XYZ":"LL","AAA":"250.00"}}}

for your sample JSON.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!