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

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

    I don't think that using a good old array is a restriction. Here is my version using an array and an extension method:

    public static string CommaQuibbling(IEnumerable list)
    {
        string[] array = list.ToArray();
    
        if (array.Length == 0) return string.Empty.PutCurlyBraces();
        if (array.Length == 1) return array[0].PutCurlyBraces();
    
        string allExceptLast = string.Join(", ", array, 0, array.Length - 1);
        string theLast = array[array.Length - 1];
    
        return string.Format("{0} and {1}", allExceptLast, theLast)
                     .PutCurlyBraces();
    }
    
    public static string PutCurlyBraces(this string str)
    {
        return "{" + str + "}";
    }
    

    I am using an array because of the string.Join method and because if the possibility of accessing the last element via an index. The extension method is here because of DRY.

    I think that the performance penalities come from the list.ToArray() and string.Join calls, but all in one I hope that piece of code is pleasent to read and maintain.

提交回复
热议问题