代码之家  ›  专栏  ›  技术社区  ›  Jacob Seleznev

如何从一个值中选择两个值

  •  2
  • Jacob Seleznev  · 技术社区  · 16 年前

    我想返回一个字符串集合,其中每秒钟的记录都是“0”,如下所示:

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

    我开始:

    customers.Select(c => new
                                          {
                                              c.Name,
                                              Second = "0"
                                          }).???
    
    4 回复  |  直到 16 年前
        1
  •  7
  •   dan    16 年前

    您需要选择多个:

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

    这将获取源列表,对于每个项,在其后面插入一个“0”。

        2
  •  2
  •   Aaronaught    16 年前

    没有任何超载 Select 或者我知道的任何其他内置扩展方法都会自动为您完成这类工作。不过,您可以为它编写自己的扩展名:

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

    然后:

    var customerNames = customers.SelectWithSeparator(c => c.Name, "0");
    
        3
  •  1
  •   Raj Kaimal    16 年前

    来自客户中的C 选择新{ 名称=C.名称, 第二=0 }

    或 客户 。选择(c=>新建 { 名称=C.名称, 第二=“0” }

    其中任何一个都能给你一瓶。可以使用.tolist()扩展名获取列表。

    但那又怎样?

    之后你想做什么?

        4
  •  1
  •   Anthony Pegram    16 年前

    替换????用分号你会得到一个 IEnumerable<'a> ,其中“a”是表示客户名称和硬编码值的匿名类型。

    var query = customers.Select(c => new { Id = c.Name, Second = 0 });
    foreach (var item in query)
    {
       // work with item.Name and item.Second
    }
    

    编辑:要从你的评论中得到你想要的,你可以这样做,你基本上已经写过了。把它包装在一个函数中,返回 IEnumerable<string>

    static IEnumerable<string> GetCustomerNames(List<Customer> customers)
    {
        foreach (Customer c in customers)
        {
            yield return c.Name;
            yield return "0";
        }
    }