Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq.js return value of (default) FirstOrDefault

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");
}
like image 742
RJB Avatar asked Dec 09 '22 07:12

RJB


2 Answers

The 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'");
like image 172
Jeff Mercado Avatar answered Jan 01 '23 11:01

Jeff Mercado


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)

like image 20
RJB Avatar answered Jan 01 '23 11:01

RJB