Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JArray.Contains issue

Tags:

c#

json.net

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

}

I want to remove the JObject corresponding to myCatalogAsJObject variable, but it doesn't work, because the answer of myjarray.Contains(myCatalogAsJObject) is false.

The problem is that myjarray actually contains it : it's the only JObject in my JArray.

If I do myCatalogAsJObject.ToString().Equals(myjarray.First.ToString()), the answer is true however.

I'm stuck.

like image 581
Adrien Budet Avatar asked Apr 28 '14 14:04

Adrien Budet


1 Answers

.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);
like image 63
D Stanley Avatar answered Oct 15 '22 13:10

D Stanley