c# - LINQ list to sentence format (insert commas & "and") -


i have linq query simple like:

var k = people.select(x=>new{x.id, x.name}); 

i want function or linq lambda, or output names in sentence format using commas , "ands".

{1, john} {2, mark} {3, george} 

to

"1:john, 2:mark , 3:george" 

i'm fine hardcoding id + ":" + name part, tostring() depending on type of linq query result. i'm wondering if there neat way linq or string.format().

public string toprettycommas<t>(   list<t> source,   func<t, string> stringselector ) {   int count = source.count;    func<int, string> prefixselector = x =>      x == 0 ? "" :     x == count - 1 ? " , " :     ", ";    stringbuilder sb = new stringbuilder();    for(int = 0; < count; i++)   {     sb.append(prefixselector(i));     sb.append(stringselector(source[i]));   }    string result = sb.tostring();   return result; } 

called with:

string result = toprettycommas(people, p => p.id.tostring() + ":" + p.name); 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -