c# with How to get list of objects from list of jobjects based on key exists or not?




find object in list c# (5)

I would not recommend LINQ. I would recommend a JSON library such as newtonsoft.json.

So you can do this:

string json = @"{
  ""Name"": ""Apple"",
  ""Expiry"": "2008-12-28T00:00:00",
  ""Price"": 3.99,
  ""Sizes"": [
    ""Small"",
    ""Medium"",
    ""Large""
  ]
}";

JObject o = JObject.Parse(json);

string name = (string)o["Name"];

// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];

// Small

Note:- this code has been copied from the samples present on the project site http://james.newtonking.com/pages/json-net.aspx

This is my code:-

List<JObject> students =[{"id":"101","name":"one","parent_id":"1"},{"id":"102","name":"two","parent_id":"2"},{"id":"103","name":"three"},{"id":"104","name":"four"}];

I tried the following code using Linq but not working

List<JObject> newStudents = students.Where(x => x.Property("parent_id").ToString() == null).ToList();


List<JObject> existedStudents = students.Where(x => x.Property("parent_id").ToString() != null).ToList();

In the above list contains 4 objects , first two objects contains parent_id key next two objects doesn't contain. How to parent_id key existed and not existed list in c#.


If the property does not exist, the Property method returns null, according to the documentation.

So do not call .ToString(), otherwise you will get a NullReferenceException. Instead:

List<JObject> newStudents = students.Where(x => x.Property("parent_id") == null).ToList();

According to the documentation, JObject.Property returns null if the property does not exist

Thus

x.Property("parent_id").ToString()

will throw a NullReferenceException if parent_id does not exist.

To check whether a property exists do not use the ToString(), just compare Property to null:

List<JObject> newStudents = students.Where(x => x.Property("parent_id") == null).ToList();

In a bind you could always deserialize the JSON and serialize it to XML, and load the XML in a XDocument. Then you can use the classic Linq to XML. When you are done take the XML, deserialize it, and serialize it back to JSON to JSON. We used this technique to add JSON support to an application that was originally built for XML, it allowed near-zero modifications to get up and running.


Can I LINQ a JSON?

No need for Linq, just use dynamic (using Json.Net)

dynamic obj = JObject.Parse(json);
Console.WriteLine((string)obj.picture.data.url);

Linq version would not be much readable

JObject jObj = JObject.Parse(json);
var url = (string)jObj.Descendants()
                    .OfType<JProperty>()
                    .Where(p => p.Name == "url")
                    .First()
                    .Value;

Documentation: LINQ to JSON





json.net