c# - How to make a natural-looking list? -


by natural-looking, mean this:

item1, item2, item3 , item4.

i know can comma-separated list string.join,

item1, item2, item3, item4

but how can make sort of list? i've got rudimentary solution:

int countminustwo = theenumerable.count() - 2; string.join(",", theenumerable.take(countminustwo)) + "and "      + theenumerable.skip(countminustwo).first(); 

but i'm pretty sure there's better (as in more efficient) way it. anyone? thanks.

you should calculate size once , store in variable. otherwise query(if it's no collection) executed everytime. also, last more readable if want last item.

string result; int count = items.count(); if(count <= 1)     result = string.join("", items); else {     result = string.format("{0} , {1}"         , string.join(", ", items.take(counter - 1))         , items.last()); } 

if readability less important , sequence quite large:

var builder = new stringbuilder(); int count = items.count(); int pos = 0; foreach (var item in items) {     pos++;     bool islast = pos == count;     bool nextislast = pos == count -1;     if (islast)         builder.append(item);     else if(nextislast)         builder.append(item).append(" , ");     else         builder.append(item).append(", "); } string result = builder.tostring(); 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -