JArray.包含问题 [英] JArray.Contains issue
问题描述
我有一个JArray,从文件中读取:
I have a JArray, read from a file :
private void RemoveCatalog(Catalog catalog) {
System.IO.StreamReader filereader = new System.IO.StreamReader(@appDirectory + "\\list");
JArray myjarray = JArray.Parse(filereader.ReadToEnd());
filereader.Close();
string json = " {\"token\":\"" + catalog.Token + "\",\"name\":\"" + catalog.Name +"\",\"logo\":\"" + catalog.Logo + "\",\"theme\":\"" + catalog.Theme + "\"}";
JObject myCatalogAsJObject = JObject.Parse(json);
myjarray.Remove(myCatalogAsJObject);
}
我想删除与myCatalogAsJObject
变量相对应的JObject,但是它不起作用,因为myjarray.Contains(myCatalogAsJObject)
的答案为假.
I want to remove the JObject corresponding to myCatalogAsJObject
variable, but it doesn't work, because the answer of myjarray.Contains(myCatalogAsJObject)
is false.
问题是myjarray
实际上包含它:它是我的JArray中唯一的JObject.
The problem is that myjarray
actually contains it : it's the only JObject in my JArray.
如果我执行myCatalogAsJObject.ToString().Equals(myjarray.First.ToString())
,答案是正确的.
If I do myCatalogAsJObject.ToString().Equals(myjarray.First.ToString())
, the answer is true however.
我被困住了.
推荐答案
.Contains
(和.Remove
)默认情况下将比较引用.由于您正在创建 new JObject
,因此该数组不包含该 instance .
.Contains
(and .Remove
) by default will compare references. Since you're creating a new JObject
, the array does not contain that instance.
您可以从数组中获取对象的实例,然后删除那个:
You could get the instance of the object from the array and remove that:
JObject match = myjarray.FirstOrDefault(j => j.token == catalog.token &&
j.name == catalog.name &&
j.logo == catalog.logo &&
j.theme == catalog.theme);
myjarray.Remove(match);
这是您的代码,简化了:
EDIT : Here is your code, simplified :
JToken match = myjarray.FirstOrDefault(j => j.ToString().Equals(myCatalogAsJObject.ToString()));
myjarray.Remove(match);
这篇关于JArray.包含问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!