Eric Lippert's challenge “comma-quibbling”, best answer?

后端 未结 27 2258
日久生厌
日久生厌 2020-12-01 06:59

I wanted to bring this challenge to the attention of the stackoverflow community. The original problem and answers are here. BTW, if you did not follow it before, you should

27条回答
  •  感情败类
    2020-12-01 07:23

    Just for fun, using the new Zip extension method from C# 4.0:

    private static string CommaQuibbling(IEnumerable list)
    {
        IEnumerable separators = GetSeparators(list.Count());
        var finalList = list.Zip(separators, (w, s) => w + s);
        return string.Concat("{", string.Join(string.Empty, finalList), "}");
    }
    
    private static IEnumerable GetSeparators(int itemCount)
    {
        while (itemCount-- > 2)
            yield return ", ";
    
        if (itemCount == 1)
            yield return " and ";
    
        yield return string.Empty;
    }
    

提交回复
热议问题