3

sequence に含まれる要素と単一の要素allを除いて、1 つの sequence のすべての要素を選択したいとします。exceptionsotherException

これよりも良い方法はありますか?新しい配列の作成を避けたいのですが、単一の要素と連結するシーケンスのメソッドが見つかりませんでした。

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

1 に答える 1

3

代替(おそらくより読みやすい)は次のとおりです。

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

または、コレクションと 1 つのアイテムを簡単に取得するための再利用可能な方法が本当に必要な場合は、次のようにします。

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

all.Except(exceptions.Plus(otherException))
于 2009-12-17T09:44:12.920 に答える