locked
How to consume any IEnumerable<T> from JavaScript

    Question

  • Hello, from JavaScript is there a way to consume an IEnumerable<T> returned from a managed WinRT function that was built using yield return? For example imagine the following C# function in a WinRT component:

    public IEnumerable<string> Foo()
    {
        yield return "a";
        yield return "b";
    }

    And in JS:

    var c1 = new WindowsRuntimeComponent1.Class1();
    var items = c1.foo();
    
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        console.log(item);
    }

    items.length returns 0 and therefore my loop never enters.

    If I change my C# code to internally use a List<string> instead, it works. For example:

    public IEnumerable<string> Foo()
    {
        var result = new List<string>();
        result.Add("a");
        result.Add("b");
        return result;
    }

    This all makes sense but...

    Is there a way to iterate an IEnumerable<T> from JS that works with results created via yield return?

    Thursday, May 23, 2013 12:51 AM

Answers

  • Nevermind, I found my own answer. You can iterate through an enumerable this way...

    for (var item = items.first() ; item.hasCurrent; item.moveNext()) {
        console.log(item.current);
    }
    

    Thursday, May 23, 2013 4:03 PM