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().
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):
This approach pretty much abuses
Skip
andTake
's ability to take negative numbers, andString.Join
's willingness to take a single parameter, so it works for one, two or more strings.This is the method is faster than the 'efficient' Join method posted by Gabe. For one and two items, it is many times faster, and for 5-6 strings, it is about 10% faster. There is no dependency on LINQ. String.Join is faster than StringBuilder for small arrays, which are typical for human-readable text. In grammar, these are called listing commas, and the last comma should always be included to avoid ambiguity. Here is the resulting code:
people.Select(x=> x.ID.ToString() + ":" + x.Name).ToList().ToListingCommaFormat();
Using the Select operation that gives you an index, this can be written as a ONE LINE extension method:
e.g.
This is not pretty but will do the job using LINQ
could be optimized by moving k.Last() computation to before the loop
Here's a method that doesn't use LINQ, but is probably as efficient as you can get:
Since it never creates a list, looks at an element twice, or appends extra stuff to the StringBuilder, I don't think you can get more efficient. It also works for 0, 1, and 2 elements in the list (as well as more, obviously).