[stringtemplate-interest] How to strip() elements from an attribute by a condition, not just null values
Igor Stolbov
Igor.Stolbov at kaspersky.com
Thu Dec 11 04:54:05 PST 2008
Hi!
Would anyone kindly help me out with the following problem:
I have a multi-valued attribute. I want to delete all values from that attribute that do not meet certain condition. How can I do that with String Templates?
For example, let's say I have an array of KeyValuePair<int, bool>. The Key is a number and the Value is true for all odd Keys. I want to write a template that, being applied to the attribute with multiple values of KeyValuePair<int, bool>, would produce a comma-separated list of only odd Keys.
Here's a simple program:
using System;
using Antlr.StringTemplate;
using KVP = System.Collections.Generic.KeyValuePair<int, bool>;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var numbers = new KVP[] {
new KVP(1, true),
new KVP(2, false),
new KVP(3, true),
new KVP(4, false),
new KVP(5, true)
};
var template = "$numbers:{$if(it.Value)$$it.Key$$endif$}; separator=\",\"$";
var onlyEvenNumbers = new StringTemplate(template);
onlyEvenNumbers.SetAttribute("numbers", numbers);
Console.Out.WriteLine(onlyEvenNumbers.ToString());
}
}
}
Naïve approach would be to use
{$if(it.Value)$$it.Key$$endif$}
template, so that only odd keys would get propagated. Good enough, but there would still remain all extra commas that separate even keys, even though the keys themselves get stripped by the template. So, the output of the program above would be
1,,3,,5
while I need to get
1,3,5
Another approach would be to transform the initial multi-value attribute to another multi-value attribute so that all even values would become null in that new attribute, and then use strip() to filter out all those nulls from it. The problem is that I do not know how to express such transformation in terms of String Templates.
Any suggestions?
Thanks!
Igor Stolbov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org:8080/pipermail/stringtemplate-interest/attachments/20081211/6724e4e2/attachment.html
More information about the stringtemplate-interest
mailing list