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

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

    Improving(hopefully) on KeithS's answer:

    string nextBit = "";
    var sb = new StringBuilder();
    foreach(Person person in list)
    {
        sb.Append(nextBit);
        sb.Append(", ");
        nextBit = String.Format("{0}:{1}", person.ID, person.Name);
    }
    sb.Remove(sb.Length - 3, 2);
    sb.Append(" and ");
    sb.Append(nextBit);
    

提交回复
热议问题