最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - linq.js return value of (default) FirstOrDefault - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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'");

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)

发布评论

评论列表(0)

  1. 暂无评论