Reputation:
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 class and instance :
public class Cus
{
public int Id { get; set; }
public string First { get; set; }
public string Last { get; set; }
public DateTime DateTime { get; set; }
}
List<Cus> o = new List<Cus>()
{
new Cus()
{
Id = 1,
First = "John",
Last = "Doe"
},
new Cus()
{
Id = 2,
First = "John",
Last = "Doe"
},
new Cus()
{
Id = 3,
First = "John",
Last = "Doe"
}
};
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.Where(x => x.Any(y => o. ????????;
}
But I want to take in my table only customer who is in List<Cus>
(using Id
)
How to do this ?
Upvotes: 1
Views: 154
Reputation: 218892
You can get all the Id's from the o
collection and use Contains
method to filter out the Customers who's Id is in the user id collection we created.
//Get the Id's from o collection.
var userIds = o.Select(f=>f.Id);
//Get the customers who's id belongs to the above collection
var customers = yourDbContext.Customers.Where(x => userIds.Contains(x.Id)).ToList();
Upvotes: 6
Reputation: 152634
Creating a list of IDs and using Contains
may be the most effective approach since it can be translated to an IN
clause in SQL:
List<int> ids = o.Select(c => c.Id).ToList();
using(DataClassesDataContext Context = new DataClassesDataContext())
{
var Customers = Context.Customers.Where(x => ids.Contains(x.Id));
}
Upvotes: 2