2017-08-09 47 views
4

這是我的代碼: -如何從基於鍵存在或不存在的工作對象列表中獲取對象列表?

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"}]; 

我使用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(); 

在上面的列表中包含4個對象,前兩個對象包含parent_id鍵旁邊的兩個對象沒有按嘗試下面的代碼不包含。如何parent_id鍵存在和不存在列表中的C#。

+0

你可以嘗試用列表而列表 ?如果你從一些API獲取JSON,只需將JSON反序列化爲列表

+0

請參閱https://stackoverflow.com/questions/18758361/can-i-linq-a-json – Anil

回答

3

按照documentation,返回null如果屬性不存在

因此

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

將拋出一個NullReferenceException如果parent_id不存在。

要檢查的屬性是否存在不使用ToString(),只是比較Propertynull

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

謝謝@Adrian。它的工作 –

1

如果該屬性不存在,Property方法返回null,according to the documentation

所以不要致電.ToString(),否則你會得到一個NullReferenceException。相反:

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

謝謝@Owen Pauling。它的工作 –

1

你應該做如下

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