C# 如何根据键是否存在从作业对象列表中获取对象列表?

C# 如何根据键是否存在从作业对象列表中获取对象列表?,c#,linq,json.net,C#,Linq,Json.net,这是我的代码:- 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"}]; List students=[{“id”:“101”,“name”:“one”,“parent_id”:“1”},{“id”:“102”

这是我的代码:-

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"}];
List students=[{“id”:“101”,“name”:“one”,“parent_id”:“1”},{“id”:“102”,“name”:“two”,“parent_id”:“2”},{“id”:“103”,“name”:“three”},{“id”:“104”,“name”:“four”};
我使用Linq尝试了以下代码,但没有成功

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();
List newStudents=students.Where(x=>x.Property(“parent_id”).ToString()==null.ToList();
列出existedStudents=students.Where(x=>x.Property(“父_id”).ToString()!=null.ToList();

在上面的列表中包含4个对象,前两个对象包含
parent\u id
key后两个对象不包含。如何
parent_id
键在c#中存在和不存在列表

如果属性不存在,则
属性
方法返回null

因此,不要调用
.ToString()
,否则您将得到
NullReferenceException
。相反:

List<JObject> newStudents = students.Where(x => x.Property("parent_id") == null).ToList();
List newStudents=students.Where(x=>x.Property(“parent_id”)==null.ToList();
根据,
JObject.Property
如果属性不存在,则返回
null

因此

如果父id不存在,将抛出
NullReferenceException

要检查属性是否存在,请不要使用
ToString()
,只需将
属性
null
进行比较即可:

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

您应该执行以下操作

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();
List newStudents=students.Where(x=>x.Property(“parent_id”).Value()==null.ToList();
列出existedStudents=students.Where(x=>x.Property(“parent_id”).Value()!=null.ToList();
您可以尝试使用列表而不是列表吗?如果您是从某个api获取JSON,只需将JSON反序列化为一个ListReference
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();