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

Time:10-09

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

CodePudding user response:

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

CodePudding user response:

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