How to select two values from one value
4 answers
There is no overloading Select
or any other built-in extension method that I know of will automatically do this for you. You could write your own extension 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");
+2
a source to share
Replace. ??? with a semicolon and you get IEnumerable<'a>
where "a is an anonymous type representing your customer name and the value you hardcoded.
var query = customers.Select(c => new { Id = c.Name, Second = 0 });
foreach (var item in query)
{
// work with item.Name and item.Second
}
Edit: To get what you want from your comments, you can do this, which you already wrote about. Just wrap it in a function that returnsIEnumerable<string>
static IEnumerable<string> GetCustomerNames(List<Customer> customers)
{
foreach (Customer c in customers)
{
yield return c.Name;
yield return "0";
}
}
+1
a source to share