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

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

    It hasn't quite been a decade since the last post so here's my variation:

        public static string CommaQuibbling(IEnumerable items)
        {
            var text = new StringBuilder();
            string sep = null;
            int last_pos = items.Count();
            int next_pos = 1;
    
            foreach(string item in items)
            {
                text.Append($"{sep}{item}");
                sep = ++next_pos < last_pos ? ", " : " and ";
            }
    
            return $"{{{text}}}";
        }
    

提交回复
热议问题