3

重複の可能性:
2 つのコレクションの比較

私は2つのリストを持っています

List<int> Foo = new List<int>(){ 1, 2, 3 };

List<int> Bar = new List<int>(){ 2, 1 };

それらが同じ要素を持っているかどうかを調べるために、私はやった

if(Foo.Except(Bar).Any() || Bar.Except(Foo).Any())
{
    //Do Something
}

ただし、これには 2 つの bool 評価が必要です。最初にそれを行いFoo.Except(Bar).Any()、次にBar.Except(Foo).Any(). 単一の評価でこれを行う方法はありますか?

4

2 に答える 2

1
        var sharedCount = Foo.Intersect(Bar).Count();
        if (Foo.Distinct().Count() > sharedCount || Bar.Distinct().Count() > sharedCount)
        {
            // there are different elements
        }
        {
            // they contain the same elements
        }
于 2012-11-24T10:07:52.347 に答える
-4

二度確認する必要はありません。このようなことをするだけです(Fooに注意してください。nullになり、関連する例外がスローされる可能性があります)

if(Foo.Intersect(Bar).Any())
{
    //Do Something
}

また、最初に、これらのリストのいずれかまたは両方が空または null であるかどうかを確認する必要があることを確認することもできます..ただし、その状況に特定の価値がある場合のみ.

于 2012-11-24T10:05:30.680 に答える