LINQ list to sentence format (insert commas & “and”)

后端 未结 17 1311
天命终不由人
天命终不由人 2021-01-12 23:33

I have a linq query that does something simple like:

var k = people.Select(x=>new{x.ID, x.Name});

I then want a function or linq lambda,

17条回答
  •  不知归路
    2021-01-13 00:26

    Here's one using a slightly modified version of my answer to Eric Lippert's Challenge which is IMHO the most concise with easy to follow logic (if you're familiar with LINQ).

    static string CommaQuibblingMod(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);  //removed braces
    }
    
    //usage
    var items = k.Select(item => String.Format("{0}:{1}", item.ID, item.Name));
    string formatted = CommaQuibblingMod(items);
    

提交回复
热议问题