How can I use System.Linq.Dynamic to check if a JSON object matches a predicate

c# dynamic-linq linq linq-to-objects


I am trying to match a complex json-object to a user-defined filter/predicate by using Json.NET and System.Linq.Dynamic. Here is my code:

var json = @"{""Name"":""Jane Doe"",""Occupation"":""FBI Consultant""}";
dynamic person = JObject.Parse(json);
var people = new[] { person };
var isMatch = people.Where("Name=@0", "Jane Doe").Any();

This gives me an error on the line with the Where-statement:

No property or field 'Name' exists in type 'Object'

If I instead use an anonymous object, by replacing the second line with this, it works as it should:

var person = new { Name = "Jane Doe", Occupation = "FBI Consultant"};

Is there another way to deserialize the json string that will allow me to query it by a string predicate to check if the json object matches?

EDIT: The json-string and Where-statement is dynamic and is supplied by the user. There are lots of properties, and i do not know their names before executing the code. Both the name of the field and the value is supplied by the user.

2/10/2017 2:58:52 PM

Popular Answer

Replace your Where statement with this:

var isMatch = people.Where(x => x.Name == "Jane Doe").Any();

Which can be simplified as:

var isMatch = people.Any(x => x.Name == "Jane Doe");

This may not be what you want, but simple System.Linq can fulfill your needs easily.

For the case you want to do this dynamically:

var isMatch = people.Any(x => x.GetValue("Name") == "Jane Doe");
2/10/2017 3:28:48 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow