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

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

    Much like the rest, this isn't better than using a string builder, but you can go (ignoring the ID, you can add it in):

    IEnumerable names = new[] { "Tom", "Dick", "Harry", "Abe", "Bill" };
    int count = names.Count();
    string s = String.Join(", ", names.Take(count - 2)
                     .Concat(new [] {String.Join(" and ", names.Skip(count - 2))}));
    

    This approach pretty much abuses Skip and Take's ability to take negative numbers, and String.Join's willingness to take a single parameter, so it works for one, two or more strings.

提交回复
热议问题