4

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");
}
RJB
  • 2,063
  • 5
  • 29
  • 34

2 Answers2

10

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'");
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • I think I might still prefer the more C#-esque formatting of using the Where clause, not sure, but I agree this is the more correct answer for using the function. Didn't realize that you have to specify what 'default' should be. Thanks! – RJB Jul 22 '14 at 16:13
  • 1
    The think you have to realize is that in C#, there are implicit parameters to the methods, the actual compile time type. This is not something you can really express in JS. C# knew what the default values were for these types so was able to fill that in. In JS, there is no real type information available so that default needs to be provided. It just so happens that `undefined` is usually adequate. – Jeff Mercado Jul 23 '14 at 01:30
4

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)

RJB
  • 2,063
  • 5
  • 29
  • 34
  • thanks for example.. finding these is a bit tough at the moment – hanzolo Feb 26 '15 at 21:45
  • I found that as well.. That link was the most helpful, but coming from using LINQ in C#, i was having some trouble relating that knowledge into this lib.. I was able to do what I needed to.. still hoping to find some more examples – hanzolo Feb 28 '15 at 00:01