LINQ:如何得到两组int的交集

本文关键字:两组 int 何得 LINQ | 更新日期: 2023-09-27 18:19:43

必须有一种方法在LINQ中比较两组结果。以下是我现有的代码,它使用HashSet在两个单独的查询后进行比较:

    public static void AssertDealershipsShareTransactionGatewayCredentialIds(long DealershipLocationId1,
        long DealershipLocationId2)
    {
        using (var sqlDatabase = new SqlDatabaseConnection())
        {
            var DealershipCredentials1 =
                sqlDatabase.Tables.DealershipLocationTransactionGateway
                    .Where(x => x.DealershipLocationId == DealershipLocationId1)
                    .Select(x => x.TransactionGatewayCredentialId);
            var DealershipCredentials2 =
                sqlDatabase.Tables.DealershipLocationTransactionGateway
                    .Where(x => x.DealershipLocationId == DealershipLocationId2)
                    .Select(x => x.TransactionGatewayCredentialId);
            var doSetsOfCredentialsMatch = new HashSet<int>(DealershipCredentials1).SetEquals(DealershipCredentials2);
            Assert.IsTrue(doSetsOfCredentialsMatch,
                "The sets of TransactionGatewayCredentialIds belonging to each Dealership did not match");
        }
    }

想法?谢谢

LINQ:如何得到两组int的交集

简单答案(这将进行1个,可能是2个数据库调用,这两个调用都只返回布尔值):

if (list1.Except(list2).Any() || list2.Except(list1).Any()) 
{
   ... They did not match ...
}

更好的答案(这将使1个数据库调用返回布尔值):

var DealershipCredentials1 =
  sqlDatabase.Tables.DealershipLocationTransactionGateway
    .Where(x => x.DealershipLocationId == DealershipLocationId1)
    .Select(x => x.TransactionGatewayCredentialId);
var DealershipCredentials2 =
  sqlDatabase.Tables.DealershipLocationTransactionGateway
    .Where(x => x.DealershipLocationId == DealershipLocationId2)
    .Select(x => x.TransactionGatewayCredentialId);
if (DealershipCredentials1.GroupJoin(DealershipCredential2,a=>a,b=>b,(a,b)=>!b.Any())
    .Union(
      DealershipCredentials2.GroupJoin(DealershipCredential1,a=>a,b=>b,(a,b)=>!b.Any())
    ).Any(a=>a))
{
... They did not match ...
}

第二种方法通过联合一个左外部联接来工作,该联接返回一个布尔值,指示是否发现了具有相同操作的右外部联接的任何不匹配记录。我还没有测试过它,但理论上,它应该从数据库中返回一个简单的布尔值。

另一种方法,本质上与第一种方法相同,但封装在一个LINQ中,因此它总是只进行一个数据库调用:

if (list1.Except(list2).Union(list2.Except(list1)).Any())
{
}

还有另一种方法:

var common=list1.Intersect(list2);
if (list1.Except(common).Union(list2.Except(common)).Any()) {}