Trying to check on the result of linq.js FirstOrDefault(), but checking for null or undefined isn't working. Having some trouble debugging it, but I can see that it is returning some sort of object.
There isn't any documentation for this method online that I could find.
I've tried:
var value = Enumerable.From(stuff).FirstOrDefault('x => x.Name == "Doesnt exist"')
if (value) {
alert("Should be not found, but still fires");
}
if (value != null)
alert("Should be not found, but still fires");
}
Trying to check on the result of linq.js FirstOrDefault(), but checking for null or undefined isn't working. Having some trouble debugging it, but I can see that it is returning some sort of object.
There isn't any documentation for this method online that I could find.
I've tried:
var value = Enumerable.From(stuff).FirstOrDefault('x => x.Name == "Doesnt exist"')
if (value) {
alert("Should be not found, but still fires");
}
if (value != null)
alert("Should be not found, but still fires");
}
Share
Improve this question
asked Jul 18, 2014 at 17:32
RJBRJB
2,1035 gold badges32 silver badges35 bronze badges
2 Answers
Reset to default 10The signatures for the FirstOrDefault()
function is:
// Overload:function(defaultValue)
// Overload:function(defaultValue,predicate)
The first parameter is always the default value to return if the collection is empty. The second parameter is the predicate to search for. Your use of the method is wrong, your query should be written as:
var value = Enumerable.From(stuff)
.FirstOrDefault(null, "$.Name === 'Doesnt exist'");
We figured out the answer as I was typing this out. Since there is so little documentation, I'll share.
You need to move the lambda into a Where clause before the FirstOrDefault().
When
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).Where('x => x == "Doesnt exist"').FirstOrDefault();
Result is undefined (correct)
When
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).Where('x => x == "Bar"').FirstOrDefault();
Result is 'Bar' (correct)
When
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).FirstOrDefault('x => x == "Bar"');
Result is 'Foo' (incorrect)