Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Select two values from one value

Tags:

c#

linq

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"
                                      }).???
like image 959
Jacob Seleznev Avatar asked Mar 23 '26 14:03

Jacob Seleznev


2 Answers

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.

like image 54
dan Avatar answered Mar 25 '26 03:03

dan


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");
like image 30
Aaronaught Avatar answered Mar 25 '26 02:03

Aaronaught



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!