【问题标题】:How do I linq like query with Dictionary in typescript?如何在打字稿中使用 Dictionary 进行 linq like 查询?
【发布时间】:2018-10-28 22:27:58
【问题描述】:

有字典接口:

interface Dictionary<T> {
    [Key: string]: T;
}

还有一些课每天重复一些练习:

export class ClassName {
   DailyReapeatCount: Dictionary<number> = {};
}

让我们初始化它:

let myClass = new ClassName();
        myClass.DailyReapeatCount['exersize_01'] = 3;
        myClass.DailyReapeatCount['exersize_02'] = 4;
        // ... and so on

然后我需要用 DailyReapeatCount 检查它是否有超过 5 的 exersize:

// pseudo code there
let isAnyExist = myClass.DailyReapeatCount.some(p => p.value > 5);

我收到 ts 通知:

无法调用类型缺少调用签名的表达式。类型 号码没有兼容的呼叫签名。”

我如何得到这个查询?

【问题讨论】:

  • 你不能用Dictionary.Count吗? (对不起,可怕的标识符,但你选择了它们)` myClass.Where(myClassName => myClassName.Count > 5).Any()? Or the jav equivalents for Any`
  • @HaraldCoppoolse 标识符没关系,我明白你的意思。如果我添加索引签名: export class ClassName { [x: string]: any; ... } 并执行 myClass.Where(myClassName => myClassName.Count > 5).Any() 我得到TypeError: myClass.Where is not a function

标签: javascript angularjs linq typescript dictionary


【解决方案1】:

使用标准的Map(与C#中的Dictionary相同):

const dictionary = new Map<string, number>([
  ["one", 1], 
  ["two", 2],
  ["five", 5],
]);

const values = Array.from(dictionary.values());
const isExist = values.some(v => v < 5);
console.log(isExist);

// In addition you can do dictionary-based things like:
console.log(dictionary.has("five")); // check is key exists

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 2013-11-22
    • 2021-10-28
    • 2013-12-26
    • 1970-01-01
    • 2011-07-28
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多