Search code examples
javascripttypescriptlinqlambdaany

Replace for loop with linq using any


I have the following code in typescript:

public executeTest(test: Test): void {
    const testFilters: Record<string> = getTestFilters();
    let isTestingRequired: boolean = false;
    
    for (let i: number = 0; i < testFilters.length; i++) {
        if(test.Name === testFilters[i].Name){
            isTestingRequired = true;
            break;
        }
    }
}

I am trying to replace the above for loop using LINQ as below, however I am getting errors.

let isTestingRequired: boolean = testFilters.any((filter.): boolean => {
    return filter.Name  === test.Name 
});

Solution

  • You will need to make your array enumerable first using Enumerable.from() like this:

    var array = [{name: "John"}, {name: "Test"}];
    
    var result = Enumerable.from(array)
      .any(obj => obj.name == "Test");
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/3.2.4/linq.min.js"></script>