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

后端 未结 27 2214
日久生厌
日久生厌 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:01

    Inefficient, but I think clear.

    public static string CommaQuibbling(IEnumerable items)
    {
        List list = new List(items);
        if (list.Count == 0) { return "{}"; }
        if (list.Count == 1) { return "{" + list[0] + "}"; }
    
        String[] initial = list.GetRange(0, list.Count - 1).ToArray();
        return "{" + String.Join(", ", initial) + " and " + list[list.Count - 1] + "}";
    }
    

    If I was maintaining the code, I'd prefer this to more clever versions.

提交回复
热议问题