How to select two values ​​from one value

I want to return a collection of strings where every second entry is "0":

        foreach (Customer c in customers)
        {
            yield return c.Name;
            yield return "0";
        }

      

I started:

customers.Select(c => new
                                      {
                                          c.Name,
                                          Second = "0"
                                      }).???

      

+2


a source to share


4 answers


you need SelectMany:

var resultList = 
    customers.SelectMany(c => new[] {c.Name, "0"});

      



this takes your original list and for each item inserts a "0" after it.

+7


a source


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


from c in clients select new {Name = c.Name, Second = 0}

or clients. Select (c => new {Name = c.Name, Second = "0"}

Either one of them will give you an IQueryable. You can get the list using the .ToList () extension.

But what then?

What do you want to do after that?

+1


a source


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







All Articles