LINQ SingleOrDefault()等效

how*_*dlo 29 javascript linq typescript typescript1.5

在Typescript中,我经常使用这种模式:

class Vegetable {
    constructor(public id: number, public name: string) {
    }
}

var vegetable_array = new Array<Vegetable>();
vegetable_array.push(new Vegetable(1, "Carrot"));
vegetable_array.push(new Vegetable(2, "Bean"));
vegetable_array.push(new Vegetable(3, "Peas"));

var id = 1;
var collection = vegetable_array.filter( xvegetable => {
    return xvegetable.id == id;
});
var item = collection.length < 1 ? null : collection[0];

console.info( item.name );
Run Code Online (Sandbox Code Playgroud)

我正在考虑创建一个类似于LINQ SingleOrDefault方法的JavaScript扩展,null如果它不在数组中,它将返回:

var item = vegetable.singleOrDefault( xvegetable => {
    return xvegetable.id == id});
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果没有创建自定义界面,是否还有其他方法可以实现这一目标

Ami*_*ich 31

您始终可以通过以下方式使用Array.prototype.filter:

var arr = [1,2,3];
var notFoundItem = arr.filter(id => id === 4)[0]; // will return undefined
var foundItem = arr.filter(id => id === 3)[0]; // will return 3
Run Code Online (Sandbox Code Playgroud)

编辑
我的答案适用于FirstOrDefault而不是SingleOrDefault.
SingleOrDefault检查是否只有一个匹配,在我的情况下(和你的代码中)你返回第一个匹配而不检查另一个匹配.

顺便说一句,如果你想实现SingleOrDefault那么你需要改变这个:

var item = collection.length < 1 ? null : collection[0];
Run Code Online (Sandbox Code Playgroud)

if(collection.length > 1)
   throw "Not single result....";

return collection.length === 0 ? null : collection[0];
Run Code Online (Sandbox Code Playgroud)


And*_*vic 22

如果你想在数组中找到一个项目,我建议你使用ES6查找方法,如下所示:

const inventory = [
    { name: 'apples', quantity: 2 },
    { name: 'bananas', quantity: 0 },
    { name: 'cherries', quantity: 5 }
];

const result = inventory.find(fruit => fruit.name === 'cherries');

console.log(result) // { name: 'cherries', quantity: 5 }
Run Code Online (Sandbox Code Playgroud)

它更快更容易阅读,因为您不需要写collection[0].

顺便说一句,如果C#SingleOrDefault找到多个元素,它会引发异常.在这里,您正在尝试进行FirstOrDefault扩展.