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

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

    public static string CommaQuibbling(IEnumerable items)
    {
      int count = items.Count();
      string answer = string.Empty;
      return "{" + 
          (count==0)  ?  ""  :  
             (  items[0] + 
                 (count == 1 ? "" :  
                     items.Range(1,count-1).
                         Aggregate(answer, (s,a)=> s += ", " + a) +
                     items.Range(count-1,1).
                         Aggregate(answer, (s,a)=> s += " AND " + a) ))+ "}";
    }
    

    It is implemented as,

    if count == 0 , then return empty,
    if count == 1 , then return only element,
    if count > 1 , then take two ranges, 
       first 2nd element to 2nd last element
       last element
    

提交回复
热议问题