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, or something that will output the names in sentence format using commas and "ands".
{1, John}
{2, Mark}
{3, George}
to
"1:John, 2:Mark and 3:George"
I'm fine with hardcoding the ID + ":" + Name
part, but it could be a ToString() depending on the type of the linq query result. I'm just wondering if there is a neat way to do this with linq or String.Format().
StringBuilder Approach
Here's an
Aggregate
with aStringBuilder
. There's some position determinations that are made to clean up the string and insert the "and" but it's all done at theStringBuilder
level.A
String.Join
approach could have been used instead but the "and" insertion and comma removal would generate ~2 new strings.Regex Approach
Here's another approach using regex that is quite understandable (nothing too cryptic).
The pattern is simply
", "
. The magic lies in theRegexOptions.RightToLeft
which makes the match occur from the right and thereby makes the replacement occur at the last comma occurrence. There is no staticRegex
method that accepts the number of replacements with theRegexOptions
, hence the instance usage.I have refined my previous answer and I believe this is the most elegant solution yet.
However it would only work on reference types that don't repeat in the collection (or else we'd have to use different means for finding out if item is first/last).
Enjoy!
Here's one using a slightly modified version of my answer to Eric Lippert's Challenge which is IMHO the most concise with easy to follow logic (if you're familiar with LINQ).
Called with:
Improving(hopefully) on KeithS's answer: