awpyix
awpyix

Reputation: 49

JArray.Contains returns false

Why does JArray.Contains always returns false, what am I doing wrong ?

var array = JArray.Parse("['abc', 'aaa']");
Console.WriteLine("1: " + array.Contains("abc"));           // false
Console.WriteLine("2: " + array.Contains((JToken)"abc"));   // false

Upvotes: 1

Views: 879

Answers (3)

Jay Imerman
Jay Imerman

Reputation: 4600

As @Orace has brilliantly deduced, the comparison by reference negates the usefulness of .Contains. However, I believe behind your question is the desire to actually perform a Contains on the array. My solution is ugly, but I take the extra step to convert the JArray to List<string>, like this:

var tmparray = JArray.Parse("['abc', 'aaa']");
var array = tmparray.ToObject<List<string>>();

if (array.Contains("aaa"))
{
   ...
}

Upvotes: 1

Bayram Eren
Bayram Eren

Reputation: 442

try this

var array = JArray.Parse("['abc', 'aaa']");
var data = array.Any(x => x.Value<string>() == "abc");
Console.WriteLine(data);

Upvotes: 0

Orace
Orace

Reputation: 8359

The implementation of Contains rely on IndexOf then IndexOfItem then IndexOfReference which use ReferenceEquals (the code is here).

Since the calls to Contains implicitly create new JToken references, those references are different and the function return false

If you call Contains with a reference that is actually in the array, it will return true:

var array = JArray.Parse("['abc', 'aaa']");
var first = array[0];

Console.WriteLine("1: " + array.Contains("abc"));           // false
Console.WriteLine("2: " + array.Contains((JToken)"abc"));   // false
Console.WriteLine("3: " + array.Contains(first));           // true

Upvotes: 1

Related Questions