代码之家  ›  专栏  ›  技术社区  ›  Binary Worrier

有没有更整洁的方法来“联合”一个项目?

  •  25
  • Binary Worrier  · 技术社区  · 15 年前

    如果我有两个序列,我想把它们都处理在一起,我可以把它们结合起来,然后离开。

    现在假设我有一个单独的项目要在两个续集之间处理。我可以通过用一个项目创建一个数组来获得它,但是有一个更整洁的方法吗?即

    var top = new string[] { "Crusty bread", "Mayonnaise" };
    string filling = "BTL";
    var bottom = new string[] { "Mayonnaise", "Crusty bread" };
    
    // Will not compile, filling is a string, therefore is not Enumerable
    //var sandwich = top.Union(filling).Union(bottom);
    
    // Compiles and works, but feels grungy (looks like it might be smelly)
    var sandwich = top.Union(new string[]{filling}).Union(bottom);
    
    foreach (var item in sandwich)
        Process(item);
    

    有没有 经核准的 这样做的方式,或者这是批准的方式?

    谢谢

    4 回复  |  直到 7 年前
        1
  •  36
  •   Bill Tür stands with Ukraine Ajay Pawar    9 年前

    一种选择是自己超载:

    public static IEnumerable<T> Union<T>(this IEnumerable<T> source, T item)
    {
        return source.Union(Enumerable.Repeat(item, 1));
    }
    

    我们就是这么做的 Concat 在里面 MoreLINQ .

        2
  •  6
  •   Kędrzu    10 年前

    考虑使用更灵活的方法:

    public static IEnumerable<T> Union<T>(this IEnumerable<T> source, params T[] items)
    {
        return source.Union((IEnumerable<T>)items);
    }
    

    适用于单个项目和多个项目。 您也可以接受空值 source 价值观:

    public static IEnumerable<T> Union<T>(this IEnumerable<T> source, params T[] items)
    {
        return source != null ? source.Union((IEnumerable<T>)items) : items;
    }
    
        3
  •  4
  •   Jon Hanna    8 年前

    我的代码中有以下内容:

    public static IEnumerable<T> EmitFromEnum<T>(this T item)
    {
      yield return item;
    }
    

    虽然打电话不是那么简单 col.Union(obj.EmitFromEnum()); 作为 col.Union(obj) 这确实意味着这个单一的扩展方法涵盖了我可能需要这样一个单一项目枚举的所有其他情况。

    更新:使用.NET核心,您现在可以使用 .Append() .Prepend() 将单个元素添加到可枚举的。对实现进行了优化,以避免产生过多的 IEnumerator 在后台实现。

        4
  •  2
  •   Glorfindel Doug L.    7 年前

    在4.7.1版的.NET核心和.NET框架中支持的新方法是使用 Append 扩展方法。

    这将使您的代码像

    var sandwich = top.Append(filling).Union(bottom);