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

后端 未结 17 1301
天命终不由人
天命终不由人 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:15

    How about this?

    var k = people.Select(x=>new{x.ID, x.Name});
    var stringified = people
                      .Select(x => string.Format("{0} : {1}", x.ID, x.Name))
                      .ToList();
    return string.Join(", ", stringified.Take(stringified.Count-1).ToArray())
           + " and " + stringified.Last();
    

提交回复
热议问题