Note that there are some explanatory texts on larger screens.

plurals
  1. POEric Lippert's challenge "comma-quibbling", best answer?
    primarykey
    data
    text
    <p>I wanted to bring this challenge to the attention of the stackoverflow community. The original problem and answers are <a href="http://blogs.msdn.com/ericlippert/archive/2009/04/15/comma-quibbling.aspx" rel="nofollow noreferrer">here</a>. BTW, if you did not follow it before, you should try to read Eric's blog, it is pure wisdom.</p> <p><strong>Summary:</strong></p> <p>Write a function that takes a non-null IEnumerable and returns a string with the following characteristics:</p> <ol> <li>If the sequence is empty the resulting string is "{}".</li> <li>If the sequence is a single item "ABC" then the resulting string is "{ABC}".</li> <li>If the sequence is the two item sequence "ABC", "DEF" then the resulting string is "{ABC and DEF}".</li> <li>If the sequence has more than two items, say, "ABC", "DEF", "G", "H" then the resulting string is "{ABC, DEF, G and H}". (Note: no Oxford comma!)</li> </ol> <p>As you can see even our very own Jon Skeet (yes, it is well known that <a href="https://stackoverflow.com/questions/305223/jon-skeet-facts">he can be in two places at the same time</a>) has posted a solution but his (IMHO) is not the most elegant although probably you can not beat its performance.</p> <p>What do you think? There are pretty good options there. I really like one of the solutions that involves the select and aggregate methods (from Fernando Nicolet). Linq is very powerful and dedicating some time to challenges like this make you learn a lot. I twisted it a bit so it is a bit more performant and clear (by using Count and avoiding Reverse):</p> <pre><code>public static string CommaQuibbling(IEnumerable&lt;string&gt; items) { int last = items.Count() - 1; Func&lt;int, string&gt; getSeparator = (i) =&gt; i == 0 ? string.Empty : (i == last ? " and " : ", "); string answer = string.Empty; return "{" + items.Select((s, i) =&gt; new { Index = i, Value = s }) .Aggregate(answer, (s, a) =&gt; s + getSeparator(a.Index) + a.Value) + "}"; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    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