【问题标题】:Add single element to a sequence for an expression将单个元素添加到表达式的序列中
【发布时间】:2009-12-17 09:41:05
【问题描述】:

假设您想要选择一个序列all 的所有元素,但序列exceptions 和单个元素otherException 中包含的元素除外。

还有比这更好的方法吗?我想避免创建新数组,但在序列上找不到将其与单个元素连接的方法。

all.Except(exceptions.Concat(new int[] { otherException }));

为了完整起见,完整的源代码:

var all = Enumerable.Range(1, 5);
int[] exceptions = { 1, 3 };
int otherException = 2;
var result = all.Except(exceptions.Concat(new int[] { otherException }));

【问题讨论】:

    标签: c# linq sequence


    【解决方案1】:

    另一种选择(也许更具可读性)是:

    all.Except(exceptions).Except(new int[] { otherException });
    

    您还可以创建一个扩展方法,将任何对象转换为 IEnumerable,从而使代码更具可读性:

    public static IEnumerable<T> ToEnumerable<T>(this T item)
    {
        return new T[] { item };
    }
    
    all.Except(exceptions).Except(otherException.ToEnumerable());
    

    或者,如果您真的想要一种可重复使用的方式来轻松获取集合和一个项目:

    public static IEnumerable<T> Plus<T>(this IEnumerable<T> collection, T item)
    {
        return collection.Concat(new T[] { item });
    }
    
    all.Except(exceptions.Plus(otherException))
    

    【讨论】:

      猜你喜欢
      • 2018-09-05
      • 1970-01-01
      • 2020-02-17
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 2022-11-29
      相关资源
      最近更新 更多