andrewducker: (Default)
andrewducker ([personal profile] andrewducker) wrote2013-01-15 02:55 pm

Things I learned today about C#

The code I've been writing to convert a list into a comma-delimited string that consists of:
var duckerBrothers = new List<string> { "Andy", "Mike", "Hugh" };
var output = string.Empty;
foreach (var duckerBrother in duckerBrothers)
{
if (output != string.Empty)
{
output += ", ";
}

output += duckerBrother;
}

Can be rewritten as:
var duckerBrothers = new List<string> { "Andy", "Mike", "Hugh" };
var output = string.Join(",", duckerBrothers);

That's what I get for assuming that there is no built-in way of doing things.
akicif: Slightly 'shopped stonehenge pic, summer solstice 2001 (Default)

[personal profile] akicif 2013-01-15 03:59 pm (UTC)(link)
And "brotherDuckers" would just look silly...

Actually, wouldn't your way, rather than the built-in way, be better if you wanted to replace the final ", " with " and "?
simont: A picture of me in 2016 (Default)

[personal profile] simont 2013-01-15 04:07 pm (UTC)(link)
I had that problem in Python once, and found it needed fewer special-case handlers than I'd expected:
    answer = ", ".join(words[:-2] + [" and ".join(words[-2:])])
Though that does rely on Python's array slice expressions having the right edge-case behaviour when the array gets shorter than 2 elements, and I don't know if C# will do the same.
pozorvlak: (Default)

[personal profile] pozorvlak 2013-01-15 07:04 pm (UTC)(link)
brothersDucker?
akicif: Slightly 'shopped stonehenge pic, summer solstice 2001 (Default)

[personal profile] akicif 2013-01-15 07:13 pm (UTC)(link)
Ha! Of course. Clearly the real reason I'm not a coder is my eye for detail....