Quickest way to comma separate a Tridion multivalue field
-
09-06-2021 - |
Question
What would be the quickest way to have a multivalue Tridion text field split into a comma separated string? In my case I am using C#, but I guess any other examples are welcome as well. This is the ugly and long way it seems:
var multiTextField = fields["multiTextField"] as TextField;
string multiCommaField = String.Empty;
for (int i = 0; i < multiTextField.Values.Count; i++)
{
multiCommaField += multiTextField.Values[i].ToString() + ",";
}
Edit: I am using .NET 3.5 and Tridion 2009 SP1
Solution
You can user LINQ:
var multiTextField = fields["multiTextField"] as TextField;
string delimeter = ",";
Console.WriteLine(multiTextField.Values.Aggregate((i, j) => i + delimeter + j))
Or in shorter (uglier) way:
((TextField) fields["multiTextField"]).Values.Aggregate((i, j) => i + "," + j))
OTHER TIPS
You haven't specified your version of Tridion or .Net in your question, but there are a few different techniques you could use to get comma separated values from the textfield.
If you're using .Net 4, I believe you could just do:
string.Join(",", multiTextField.Values);
as long as multiTextField.Values
implements IList.
If you're using .Net 3.5 or earlier, I believe that the string.Join()
function requires an array rather than IList
.
There was a pretty good discussion regarding the options here String Join on a List (.Net 4)
or here Trying to string.Join an IList (.Net 4)
or here Creating a comma separated list from IList (.Net 3.5)
Evaluate the expression. A multi-valued text field is already a comma-separated string "under the water", so you could just grab it in your Dreamweaver layer like this:
@@(Component.multiValueField)@@
Have you tried multiTextField.Values.ToArray().Join(",")
?