Home > Mobile >  JArray.Contains returns false
JArray.Contains returns false

Time:05-31

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

CodePudding user response:

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

CodePudding user response:

try this

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