Note that there are some explanatory texts on larger screens.

plurals
  1. POSerialize a HashSet<String> with LinQ
    primarykey
    data
    text
    <p>I'd like to take a <code>HashSet&lt;String&gt;</code> and elegantly convert it to a string. I can iterate like so:</p> <pre><code>HashSet&lt;String&gt; words = new HashSet&lt;string&gt;() { "alpha", "beta", "delta" }; string joined = ""; foreach (var w in words) joined += w + ","; if(joined.Length &gt; 0) joined = joined.SubString(0,joined.Length-1); // remove final comma </code></pre> <p>Is there a <code>LinQ</code> way to do this elegantly and efficiently?</p> <p>The only way I can think of doing this is by converting it to an array first:</p> <pre><code>HashSet&lt;String&gt; words = new HashSet&lt;string&gt;() { "alpha", "beta", "delta" }; string joined = String.Join(",",words.ToArray()); </code></pre> <p>But, then I'm doing a double conversion. Would there be some handy-dandy LinQ expression that's efficient and clear?</p> <p><strong>ANSWER 1 (from marr's idea)</strong></p> <pre><code>public static string JoinItems(this IEnumerable&lt;string&gt; items, string joiner) { StringBuilder sb = new StringBuilder(""); foreach (var i in items) sb.AppendFormat("{0}{1}",i,joiner); if(sb.Length&gt;0) return sb.Remove(sb.Length - joiner.Length, joiner.Length).ToString(); else return sb.ToString(); } </code></pre> <p><em>ANSWER 2 using an Enumerator (from Martin's solution)</em></p> <pre><code>public static string JoinItems&lt;T&gt;(this IEnumerable&lt;T&gt; items, string delim) { var sb = new StringBuilder(); var i = items.GetEnumerator(); if (i.MoveNext()) { sb.Append(i.Current); while (i.MoveNext()) { sb.Append(delim); sb.Append(i.Current); } } return sb.ToString(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload