LINQ SingleOrDefault()等效 [英] LINQ SingleOrDefault() equivalent

查看:94
本文介绍了LINQ SingleOrDefault()等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Typescript, I use this pattern often:

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 );

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

I am thinking about creating a JavaScript extension similar to the LINQ SingleOrDefault method where it returns null if it's not in the array:

var item = vegetable.singleOrDefault( xvegetable => {
    return xvegetable.id == id});

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

My question is whether there is another way to achieve this without creating a custom interface?

推荐答案

您可以随时使用 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

编辑

我的回答适用于 FirstOrDefault 而不是 SingleOrDefault

SingleOrDefault 检查是否只有一个匹配,在我的情况下(和你的代码中)你返回第一个匹配而不检查另一个匹配。

Edit
My answer applies to FirstOrDefault and not to SingleOrDefault.
SingleOrDefault checks if there is only one match and in my case (and in your code) you return the first match without checking for another match.

BTW,如果你想实现 SingleOrDefault 那么你需要改变这个:

BTW,If you wanted to achieve SingleOrDefault then you would need to change this:

var item = collection.length < 1 ? null : collection[0];

进入

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

return collection.length === 0 ? null : collection[0];

这篇关于LINQ SingleOrDefault()等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆