How to get a list of objects from a task list based on a key or not?

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 did not work

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();

The above list contains 4 objects, the first two objects contain the parent_idkey, the next two objects do not contain. How the parent_idkey existed and did not exist in the C # list.

+4
source share
3 answers

According to the documentation , JObject.Propertyreturns nullif the property does not exist

In this way,

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

will throw NullReferenceExceptionif parent_iddoes not exist.

, , ToString(), Property null:

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

, Property null, .

.ToString(), NullReferenceException. :

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

You should do the following:

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
source

Source: https://habr.com/ru/post/1683342/


All Articles