K.Z
K.Z

Reputation: 5075

C# LINQ select from List where value is not contained in database

I am working on .NET CORE 5 application along with Entity Framework CORE. I have list of string and I need to filter out records from list which does not exist in database so that I can only process those records. In following attempt I am getting null error. I am using Contain but not sure it is really suitable if I have records about 4000 for example

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

Upvotes: 0

Views: 383

Answers (3)

K.Z
K.Z

Reputation: 5075

found answer;

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

Upvotes: 0

xC0bra
xC0bra

Reputation: 36

var d2 = PaymentSourceReferences.Where(x => !db.myTable.Any(t => t.Id == x)).ToList();

Upvotes: 2

Yaseen
Yaseen

Reputation: 336

These when your PaymentSourceReference is null. You cannot pass null to Contains You can assign empty string if its null eg. PaymentSourceReference??String.Empty

Below I have modified your code you can check inside contains method


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

Upvotes: 1

Related Questions