开发者

How to Select two values from one value

开发者 https://www.devze.com 2022-12-28 15:49 出处:网络
I want to return a collection of strings where every second record is \"0\" similar to this: foreach (Customer c in customers)

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");


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?


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";
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消