Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查两个列表在单个评估中是否具有相同的元素_C#_List - Fatal编程技术网

C# 检查两个列表在单个评估中是否具有相同的元素

C# 检查两个列表在单个评估中是否具有相同的元素,c#,list,C#,List,可能重复: 我有两张单子 List<int> Foo = new List<int>(){ 1, 2, 3 }; 但这需要两个布尔评估。首先它执行Foo.Except(Bar).Any(),然后执行Bar.Except(Foo).Any()。有没有办法在一次评估中做到这一点?您不必检查两次。 只需这样做(注意Foo,它可以为null并抛出相关异常) 您可能还需要首先检查,您必须检查这些列表中的一个或两个是否为空或空。。但前提是这种情况对你有任何特殊的价值。例如,它返回

可能重复:

我有两张单子

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

但这需要两个布尔评估。首先它执行
Foo.Except(Bar).Any()
,然后执行
Bar.Except(Foo).Any()
。有没有办法在一次评估中做到这一点?

您不必检查两次。 只需这样做(注意Foo,它可以为null并抛出相关异常)


您可能还需要首先检查,您必须检查这些列表中的一个或两个是否为空或空。。但前提是这种情况对你有任何特殊的价值。

例如,它返回true,但应该是false。我认为这不是海报想要的。它会让您知道这两个元素之间是否有共享的元素,而不是所有元素是否都共享。如果Foo有“共享”元素,并且Bar(至少有一个)在列表中以相同的顺序包含相同的元素,则返回true。@Nikhil Agrawal您所说的“即使列表中包含..,则其进入”是什么意思?我不明白,
Union
Distinct
应用于结果。因此,如果初始序列中有不明显的元素,那么计数可能不相同。这是预期的结果——找出两个集合中是否有相同的元素,或者找出集合中的所有元素是否相同(但可能顺序不同)?@lazyberezovsky:顺序并不重要。只是检查是否有任何元素存在于Foo中而不存在于Bar中,或者存在于Bar中而不存在于Foo中。
        var sharedCount = Foo.Intersect(Bar).Count();
        if (Foo.Distinct().Count() > sharedCount || Bar.Distinct().Count() > sharedCount)
        {
            // there are different elements
        }
        {
            // they contain the same elements
        }
if(Foo.Except(Bar).Any() || Bar.Except(Foo).Any())
{
    //Do Something
}
if(Foo.Intersect(Bar).Any())
{
    //Do Something
}
        var sharedCount = Foo.Intersect(Bar).Count();
        if (Foo.Distinct().Count() > sharedCount || Bar.Distinct().Count() > sharedCount)
        {
            // there are different elements
        }
        {
            // they contain the same elements
        }