2

I have a SQL table :

Id  FirstName   LastName    DateTime
1   John        Doe         2016-09-27 20:45:52.293
2   John        Doe         2016-09-27 20:45:53.620
3   John        Doe         2016-09-27 20:46:02.370
4   John        Doe         2016-09-27 20:46:02.533
5   John        Doe         2016-09-27 20:46:02.680
6   John        Doe         2016-09-27 20:46:02.820

And one List<Int> :

List<int> ids = new List<int>(){ 2, 3, 5 }

I use Linq To Sql class for get all record in my sql table. I do :

using(DataClassesDataContext Context = new DataClassesDataContext())
{
    var Customers = Context.Customers;
}

I want to know if all the ids on the list are present in the table and if not, find out what line is not present

What is the best way to do this ?

  • Possible duplicate of [How would you do a "not in" query with LINQ?](http://stackoverflow.com/questions/183791/how-would-you-do-a-not-in-query-with-linq) – Keith Nicholas Sep 27 '16 at 21:14

2 Answers2

0

You can use Any in LINQ to find all missing customer details

var missingCustomers = Customers.Where(c => !ids.Any(i => i == c.Id)).ToList();
techspider
  • 3,370
  • 13
  • 37
  • 61
0

"I want to know if all the ids on the list are present in the table and if not, find out what line is not present"

To find out if all the ids on the list are present in the table:

bool check = ids.All(i => Customers.Select(s => s.Id).Contains(i));

To find out what customers are not present (similar to some other answers here):

var missingCustomers = Customers.Where(c => !ids.Contains(c.Id)).ToList();

Edit

For the reverse (find missing Ids in table):

var allTableIds = Customers.Select(s => s.Id).ToList();
var missingCustomersIDs = ids.Where(c => !allTableIds.Contains(c)).ToList();
Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41