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

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

    Here's my submission. Modified the signature a bit to make it more generic. Using .NET 4 features (String.Join() using IEnumerable), otherwise works with .NET 3.5. Goal was to use LINQ with drastically simplified logic.

    static string CommaQuibbling(IEnumerable items)
    {
        int count = items.Count();
        var quibbled = items.Select((Item, index) => new { Item, Group = (count - index - 2) > 0})
                            .GroupBy(item => item.Group, item => item.Item)
                            .Select(g => g.Key
                                ? String.Join(", ", g)
                                : String.Join(" and ", g));
        return "{" + String.Join(", ", quibbled) + "}";
    }
    

提交回复
热议问题