Hello,
I try to get the index of the elements in a Select statement at the template level, but I can’t.
I’ve tried with the IndexOf() function like this (this works in a foreach instruction) :
<<var [pumpData = Query.GetDescendants(Entity, "Pump").Select(p => new {
pump = p[“Id”],
position = p.IndexOf()
})]>>
and I’ve tried also this :
<<var [pumpData = Query.GetDescendants(Entity, "Pump").Select((p1, i) => new {
pump = p1[“Id”],
position = i
})]>>
How can I do that ? I can work only at level template, not in code behind.
Thanks so much for your reply
Summary
You can’t obtain the element index inside a Select expression when you are working only with the Aspose.Words template language. The Select overload that provides the index (Select((item, index) => …)) is not supported in the template syntax, and the IndexOf() function works only inside a foreach block.
Why it happens
The template language is a limited subset of C# / LINQ that Aspose.Words evaluates at runtime. It supports the basic Select overload that takes a single argument (Select(item => …)). The overload that supplies the index (Select((item, index) => …)) and the IndexOf() method are not exposed in this context, so the engine cannot resolve the index value.
What to do next
Use a foreach block if you need the index. Inside a foreach you can call item.IndexOf() to get the position of the current element.
Compute the index in code‑behind (C# / Java / etc.) and pass it to the template as part of the data source. For example, build a list of anonymous objects where you set position = i in your own code and then bind that list to the template.
Alternative workaround: If you must stay in the template, you could create a separate query that returns the whole collection, then use Query.GetDescendants(...).ToList().IndexOf(p) inside the Select, but this is inefficient and not recommended.
In short, the template language does not provide a direct way to get the index inside Select; you need to either switch to a foreach or calculate the index outside the template and pass it in.
If you have the possibility to add a small piece of code‑behind, that is the most reliable solution.
I could not fully verify this explanation against the retrieved sources. Please double-check the behaviour in your environment and confirm the exact SDK/version.
SDK version unclear — refer to the official release notes before applying this guidance.
Basically, I agree with the auto-reply. If possible, a template should be modified according to the provided suggestions. If not, then please provide more details on your goal and maybe, we will be able to suggest a workaround.