Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Convert .net IEnumerable to JS array

0
0
Hello Petr,

How can I convert .net array into JS array without modification of the script?

You can use the script engine as a helper. Here's a simple extension method that converts a .NET collection to a JavaScript array:
internalstaticclass EnumerableExtensions {
    publicstaticobject ToScriptArray<T>(this IEnumerable<T> collection, ScriptEngine engine) {
        dynamic array = engine.Evaluate("([])");
        foreach (var item in collection) {
            array.push(item);
        }
        return array;
    }
}
And here's how you might use it:
var foo = Enumerable.Range(100, 10);
engine.Script.foo = foo.ToScriptArray(engine);
engine.Execute(@"
    for (var i = 0; i < foo.length; ++i) {
        var item = foo[i];
        // do something
    }
");
Another possibility might be to use a wrapper to make your collection look more like a JavaScript array:
publicclass ArrayLikeWrapper : ArrayList {
    public ArrayLikeWrapper(IEnumerable collection) {
        foreach (var item in collection) {
            Add(item);
        }
    }
    publicint length => Count;
    publicint push(object item) {
        return Add(item) + 1;
    }
}
And then:
var foo = Enumerable.Range(100, 10);
engine.Script.foo = new ArrayLikeWrapper(foo);
// etc.
So there's more than one way to do it.

Good luck!

Viewing all articles
Browse latest Browse all 2297

Latest Images

Trending Articles





Latest Images