I want to return a collection of strings where every second record is "0" similar to this:
foreach (Customer c in customers)
{
yield return c.Name;
yield return "0";
}
I started:
customers.Select(c => new
{
c.Name,
Second = "0"
}).???
you need SelectMany:
var resultList =
customers.SelectMany(c => new[] {c.Name, "0"});
this takes your source list, and for each item, inserts a "0" after it.
There isn't any overload of Select or any other built-in extension method I know of that would do this kind of thing automatically for you. You could write your own extension for it though:
public static class EnumerableExtensions
{
public static IEnumerable<TResult> SelectWithSeparator<T, TResult>(
this IEnumerable<T> source,
Func<T, TResult> selector,
TResult separator)
{
if (selector == null)
throw new ArgumentNullException("selector");
foreach (T item in source)
{
yield return selector(item);
yield return separator;
}
}
}
Then:
var customerNames = customers.SelectWithSeparator(c => c.Name, "0");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With