JArray.Contains issue

对着背影说爱祢 提交于 2019-12-23 10:40:34

问题


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.


回答1:


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



回答2:


As for the Contains part of your question, here's my take on a typed JArray.Contains:

public static bool ContainsTyped<T>(this JArray arr, T item)
{
    return arr.Any(it =>
    {
        T typed;
        try
        {
            typed = it.ToObject<T>();
        }
        catch (JsonException e)
        {
            Console.WriteLine("Couldn't parse array item {0} as type {1}: {2}", it, typeof(T), e);
            return false;
        }

        return typed.Equals(item);
    });
}

Now simply implement Equals on your type (e.g. Catalog) and call arr.ContainsTyped(catalog).



来源:https://stackoverflow.com/questions/23343771/jarray-contains-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!