4

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#.

Anil
  • 3,722
  • 2
  • 24
  • 49
siva kishore
  • 43
  • 1
  • 6

3 Answers3

3

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();
adjan
  • 13,371
  • 2
  • 31
  • 48
2

You should do as follows

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


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

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();
Owen Pauling
  • 11,349
  • 20
  • 53
  • 64