【问题标题】:C# LINQ select from List where value is not contained in databaseC# LINQ 从列表中选择值不包含在数据库中
【发布时间】:2021-11-28 08:25:59
【问题描述】:

我正在开发 .NET CORE 5 应用程序以及 Entity Framework CORE。我有字符串列表,我需要从列表中过滤掉数据库中不存在的记录,以便我只能处理这些记录。在接下来的尝试中,我收到了 null 错误。我正在使用 Contain,但如果我有大约 4000 条记录,我不确定它是否真的合适

error

   Value cannot be null. (Parameter 'value')

Code

 List<string> PaymentSourceReferences = new List<string>();
        PaymentSourceReferences.Add("e3gdf210-f933-ec11-xxxx-00505691aaaa");
        PaymentSourceReferences.Add("gg34b580-f843-ec11-xxxx-00505691rrrr");
        PaymentSourceReferences.Add("43gf353d-f8fe-ec11-xxxx-00505691tttr");
        PaymentSourceReferences.Add("h4gd5170-7943-ec11-xxxx-00505687bbbb");
        PaymentSourceReferences.Add("4gdv5170-7965-ec11-xxxx-005056874gdg");

   var d2 = (from x in PaymentSourceReferences
             where !x.Contains(db.myTable)
             select PaymentSourceReference).ToList();

【问题讨论】:

    标签: c# linq entity-framework-core .net-5


    【解决方案1】:
    var d2 = PaymentSourceReferences.Where(x => !db.myTable.Any(t => t.Id == x)).ToList();
    

    【讨论】:

      【解决方案2】:

      当您的 PaymentSourceReference 为空时这些。 您不能将 null 传递给 Contains 如果它为空,您可以分配空字符串 例如。 PaymentSourceReference??String.Empty

      下面我修改了你的代码,你可以在 contains 方法中检查

      
      List<string> PaymentSourceReferences = new List<string>();
              PaymentSourceReferences.Add("e3gdf210-f933-ec11-xxxx-00505691aaaa");
              PaymentSourceReferences.Add("gg34b580-f843-ec11-xxxx-00505691rrrr");
              PaymentSourceReferences.Add("43gf353d-f8fe-ec11-xxxx-00505691tttr");
              PaymentSourceReferences.Add("h4gd5170-7943-ec11-xxxx-00505687bbbb");
              PaymentSourceReferences.Add("4gdv5170-7965-ec11-xxxx-005056874gdg");
      
        string PaymentSourceReference = null;
         var d2 = (from x in PaymentSourceReferences
                   where !x.Contains(PaymentSourceReference??String.Empty)
                   select PaymentSourceReference).ToList();
      

      【讨论】:

      • 感谢您提供详细信息,我只想从字符串列表中提取数据库中不存在的那些记录?其中 !x.Contains(dbContext.myTable.Id == x)
      【解决方案3】:

      找到答案;

        var existingPaymentReferences = 
                 (from payment in db.BoPcnPayments
                  where PaymentSourceReferences.Contains(payment.PaymentSourceReference)
                  select payment.PaymentSourceReference).ToList();
      
        var paymentReferencesToProcess = 
                 (from csvPayements in PaymentSourceReferences
                  where !existingPaymentReferences.Contains(csvPayements)
                  select csvPayements).ToList();
      

      【讨论】:

        猜你喜欢
        • 2017-05-19
        • 2019-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-01
        • 2021-10-03
        相关资源
        最近更新 更多