tags:

views:

75

answers:

4

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"
                                      }).???
+1  A: 

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

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

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

But then what?

What do you want to do after this?

Raj Kaimal
I want a collection of strings where every second record is "0"
Jacob Seleznev
I see. What is wrong with your first aproach? Are you asking how to do it with lambda expressions?
Raj Kaimal
Yes, I want to lose that foreach!
Jacob Seleznev
+1  A: 

Replace .??? with a semi-colon and you'll get an IEnumerable<'a>, where 'a is an anonymous type representing your customer's 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've basically already written. Just wrap it up in a function returning an IEnumerable<string>

static IEnumerable<string> GetCustomerNames(List<Customer> customers)
{
    foreach (Customer c in customers)
    {
        yield return c.Name;
        yield return "0";
    }
}
Anthony Pegram
+2  A: 

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");
Aaronaught
+5  A: 

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.

dan
I doubted, then I tested. Neat.
Anthony Pegram
Very nice. Good to know!
Raj Kaimal